Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在SQL中查找年中最常见的元素_Sql_Sqlite_Subquery - Fatal编程技术网

在SQL中查找年中最常见的元素

在SQL中查找年中最常见的元素,sql,sqlite,subquery,Sql,Sqlite,Subquery,我有一个表,有三个属性,年份,品种和颜色。例如: ╔════╤═════════╤═══════╤══════╗ ║ id │ breed │ color │ year ║ ╠════╪═════════╪═══════╪══════╣ ║ 01 │ pug │ black │ 2019 ║ ╟────┼─────────┼───────┼──────╢ ║ 02 │ pug │ black │ 2019 ║ ╟────┼─────────┼───────┼──────╢

我有一个表,有三个属性,年份,品种和颜色。例如:

╔════╤═════════╤═══════╤══════╗
║ id │ breed   │ color │ year ║
╠════╪═════════╪═══════╪══════╣
║ 01 │ pug     │ black │ 2019 ║
╟────┼─────────┼───────┼──────╢
║ 02 │ pug     │ black │ 2019 ║ 
╟────┼─────────┼───────┼──────╢
║ 03 │ poodle  │ brown │ 2019 ║
╟────┼─────────┼───────┼──────╢
║ 04 │ pug     │ white │ 2013 ║
╟────┼─────────┼───────┼──────╢
║ 05 │ poodle  │ brown │ 2013 ║ 
╟────┼─────────┼───────┼──────╢
║ 06 │ poodle  │ white │ 2010 ║  
╟────┼─────────┼───────┼──────╢
║ 07 │ bulldog │ white │ 2010 ║
╟────┼─────────┼───────┼──────╢
║ 08 │ husky   │ brown │ 2012 ║
╟────┼─────────┼───────┼──────╢
║ 09 │ pug     │ black │ 2013 ║
╟────┼─────────┼───────┼──────╢
║ 10 │ husky   │ brown │ 2014 ║
╚════╧═════════╧═══════╧══════╝
创建表

create table dogs (
 id     char(5),
 breed      char(10),
 year       int,
 color      char(10),
 primary key (id)
 );

对于一只狗的每一年,我需要找到最常见的品种和最常见的狗的颜色,如果有领带,列出所有的领带。我尝试了以下方法:

SELECT d.year, d.breed,COUNT(d.breed),d.color,COUNT(v.color)
FROM dogs d
GROUP BY d.year,d.breed,d.color;

这基本上只是让我知道每年不同的品种和每种颜色有多少。我将如何回答上述问题?我也在使用SQLite

如果您的SQLite版本是
3.25.0
或更高版本,我们可以尝试使用
RANK

WITH cte AS (
    SELECT d.year, d.breed, d.color, COUNT(d.breed) AS cnt,
        RANK() OVER (ORDER BY COUNT(d.breed) DESC) rnk
    FROM dogs d
    GROUP BY d.year, d.breed, d.color
)

SELECT year, breed, color, cnt
FROM cte
WHERE rnk = 1;

如果你的SQLite版本不支持窗口函数,并且你期望有类似于这个前进的报告需求,那么考虑升级。

下面展示了如何计算,对于每一年,最频繁的品种, 不需要排名

制定一个单独的(结构相同的)查询来确定每年最常见的颜色可能是最容易的

with frequencies as (select year, breed, count(*) as breedcount from dogs GROUP BY breed, year),
     maxes       as (select year, max(breedcount) mx from frequencies GROUP BY year)
select frequencies.year year, breed, mx
     from frequencies JOIN maxes ON frequencies.year = maxes.year
     where breedcount = mx ORDER BY year ;
输出(带标题)
“我需要找到最常见的品种和采用的最常见的狗颜色”-是“对于一年和每个品种,找到最常见的狗颜色”-还是不管一年中的哪个品种的单一颜色?可以附加result@Dai我需要品种和颜色的笛卡尔乘积。这意味着如果2019年有2个品种和3种颜色最常见,那么2019年它将返回6行。
year|breed|mx
2010|bulldog|1
2010|poodle|1
2012|husky|1
2013|pug|2
2014|husky|1
2019|pug|2