【问题标题】:Finding most common elements in year in SQL在 SQL 中查找一年中最常见的元素
【发布时间】:2019-10-10 04:53:19
【问题描述】:

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

╔════╤═════════╤═══════╤══════╗
║ 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。

【问题讨论】:

  • “我需要找到最常见的品种和最常采用的狗颜色” - 是“对于年份和每个品种,找到最常见的狗颜色” - 或者不管是单一颜色当年的品种?
  • 可以附加预期结果
  • @Dai 我需要绑定的品种和颜色的笛卡尔积。这意味着如果有 2 个品种和 3 种颜色在 2019 年最常见,那么它将返回 2019 年的 6 行。

标签: sql sqlite subquery


【解决方案1】:

如果您的 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 版本不支持窗口函数,并且您希望未来有类似的报告要求,那么请考虑升级。

【讨论】:

    【解决方案2】:

    下面显示了如何计算每年最常见的品种, 无需排名。

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

    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 ;
    

    输出(带标题)

    year|breed|mx
    2010|bulldog|1
    2010|poodle|1
    2012|husky|1
    2013|pug|2
    2014|husky|1
    2019|pug|2
    

    【讨论】:

      猜你喜欢
      • 2010-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-11
      相关资源
      最近更新 更多