我有一个列中包含值的SQL列,我想知道排名格式中哪些值最多。例如,如果我在名为List的表中有数据,并且列具有如下所示的值:
COLUMN
one
five
five
five
three
two
eight
nine
two
one
two
two
sql应该返回前三个值,即Two,Five和One。如何在SQL中完成此操作。请注意我使用的是MYSQL。
此外,如果每个Column值都有一个时间戳,是否可以找出一周内发生的值最多而无需手动输入一周的开始和结束?
答案 0 :(得分:1)
试
set @l:=0, @n:=0, @w:=current_timestamp;
select w, c, n, l
from (
select
w
, c
, n
, @l:=case when @n=n and @w=w then @l
when @n<>n and @w=w then @l+1
else 1 end l
, @n:=n
, @w:=w
from (
select
col c
, count(1) n
, adddate(datecol, INTERVAL 1-DAYOFWEEK(datecol) DAY) w
from list
group by col, adddate(datecol, INTERVAL 1-DAYOFWEEK(datecol) DAY)
order by adddate(datecol, INTERVAL 1-DAYOFWEEK(datecol) DAY), count(1) desc
) s
) t
where l<=3
order by w asc, n desc;
答案 1 :(得分:1)
虽然我提供了答案,但我应该警告你,如果你想要一致的结果,你必须按顺序指定其他列。 假设您的表格如下:
('one'),
('five'),
('five'),
('five'),
('three'),
('two'),
('eight'),
('nine'),
('two'),
('one'),
('two'),
('two'),
('nine')
因此,您有4个five
,3个two
和2个nine
和one
。哪一个会在结果中出现?我认为你应该自己指定它。
如果你想获得所有行数,那么数量等于前3个计数,在SQL Server和PostgreSQL中你可以这样做:
;with cte as (
select
col,
count(*) as cnt,
dense_rank() over(order by count(*) desc) as rnk
from list
group by col
)
select col, cnt
from cte
where rnk <= 3
答案 2 :(得分:0)
要获得MySQL中最常见的三个:
select col
from t
group by col
order by count(*) desc
limit 3;
如果你想获得前3个计数 - 即使有重复 - 那么查询会更麻烦。这是一种方式:
select c.col
from (select col, count(*) as cnt
from t
group by col
order by cnt desc
limit 3
) cols join
(select col, count(*) as cnt
from t
group by col
) c
on cols.cnt = c.cnt;
最后,我知道如果没有指定定义周的日期,就无法获取特定周的记录。
答案 3 :(得分:0)
考虑您的表有2列[Col1]和[Time]:
select col1 , COUNT(col1) as QTY from TBL1
where [time] between CURRENT_TIMESTAMP and CURRENT_TIMESTAMP-7
group by col1
order by QTY desc