每年在SQL中查找最常用的数据

时间:2017-10-22 08:28:17

标签: sql

表A:

Years Data
2000  A
2000  B
2000  C
2000  C
2000  D
2001  A
2001  B
2001  B
2002  B
2002  D
2002  D

我想输出:

Years Data
2000  C
2001  B
2002  D

我的解决方案:

SELECT DISTINCT Years, Data
FROM
(
   SELECT Years, Data, COUNT(*) AS _count
   FROM TableA
   GROUP BY Years, Data
) a1
ORDER BY Years, _count DESC

但它有一个问题:

  如果指定了ORDER BY

SELECT DISTINCT项必须出现在选择列表中。

如何更正我的SQL代码?

4 个答案:

答案 0 :(得分:1)

假设您的数据库支持row_number(),您可以这样做:

let objectExample = { key1: { prop1: '123', prop2: 'def' }, key2: { prop1: '456', prop2: 'ghi' }, key3: { prop1: '789', prop2: 'abc' } };

let objectSorted = {};
 Object.keys(objectExample).sort((key1,key2) => {
    return objectExample[key1].prop2.localeCompare(objectExample[key2].prop2);
}).forEach((element) => {
    objectSorted[element] = objectExample[element];
});

console.log(JSON.stringify(objectSorted));

See a live demo on rextester.

答案 1 :(得分:0)

试试这个:

select t.Years, t.[Data]
from (
    select *, count(*) cnt
    from TableA
    group by years, [Data]
    ) t
left join (
    select Years, max(cnt) maxCnt
    from (
        select *, count(*) cnt
        from TableA
        group by years, [Data]
    ) t
    group by Years
    ) tt on t.Years = tt.Years   -- tt is a view that gives you max count of each year
where t.cnt = tt.maxCnt          -- you need `years`, `[Data]` that its count is max count
order by years;

SQL Fiddle Demo

另一种方法是在支持它的DBMS中使用rank()

;with t as (
    select *, count(*) cnt
    from TableA
    group by years, [Data]
), tt as (
    select *, rank() over (partition by years order by cnt desc) rn
    from t
)
select years, [Data]
from tt
where rn = 1
order by years;

SQL Fiddle Demo

答案 2 :(得分:0)

如果您正在使用oracle,则可以使用函数STATS_MODE

  select years, stats_mode(data)
    from tablet
group by years;

https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions154.htm

答案 3 :(得分:0)

您的错误是"ORDER BY items must appear in the select list if SELECT DISTINCT is specified."

这意味着您在ORDER BY中放置了一些不在SELECT中的内容。在这种情况下, _count DESC不在SELECT语句中

SELECT DISTINCT Years, Data, _count DESC
FROM
(
   SELECT Years, Data, COUNT(*) AS _count
   FROM TableA
   GROUP BY Years, Data
) a1
ORDER BY Years, _count DESC