1

我有一个 SQL 列,列中有值,我想知道哪些值在排名格式中出现次数最多。例如,如果我在一个名为 List 的表中有数据,并且一列的值如下所示:

COLUMN
one
five
five
five
three
two
eight
nine
two
one
two
two

sql 应该返回前 3 个值,即二、五和一。这如何在 SQL 中完成。请注意我使用的是 MYSQL。

此外,如果每个 Column 值都有一个时间戳,是否可以找出一周内出现次数最多的值,而无需手动输入一周的开始和结束?

4

4 回答 4

1

try

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;

demo

于 2013-08-11T11:44:39.070 回答
1

虽然 TI 提供了答案,但我应该警告您,如果您想要一致的结果,您必须按顺序指定其他列。假设您的表格如下:

('one'),
('five'),
('five'),
('five'),
('three'),
('two'),
('eight'),
('nine'),
('two'),
('one'),
('two'),
('two'),
('nine')

所以你有 4 个five, 3 个two和 2 个nineone。哪一个会出现在结果中?我认为你应该自己指定。
如果您想获取所有行数等于前 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

=> sql 小提琴示例

于 2013-08-11T12:07:01.363 回答
0

consider your table has 2 coloumns [Col1] and [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 
于 2014-11-03T17:50:51.840 回答
0

To get the three most common in MySQL:

select col
from t
group by col
order by count(*) desc
limit 3;

If you want to get the top 3 counts -- even if there are duplicates -- then the query is a bit more cumbersome. Here is one way:

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;

Finally, I know of no way of getting records for a particular week without specifying the dates to define the week.

于 2013-08-11T12:59:39.327 回答