1

列に値を含む SQL 列があり、ランク付けされた形式で最も多く発生する値を知りたいです。たとえば、List というテーブルにデータがあり、列に次のような値があるとします。

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

SQL は、2、5、1 の上位 3 つの値を返す必要があります。これをSQLでどのように行うことができますか。私はMYSQLを使用していることに注意してください。

また、各列の値にタイム スタンプが設定されている場合、週の開始日と終了日を手動で入力しなくても、その週に最も多く発生した値を見つけることができますか?

4

4 に答える 4

1

TI は回答を提供しますが、一貫した結果が必要な場合は、順序で他の列を指定する必要があることを警告する必要があります。次のようなテーブルがあるとします。

('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

=> SQLフィドルの例

于 2013-08-11T12:07:01.363 に答える
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 に答える
0

テーブルに [Col1] と [Time] の 2 つの列があるとします。

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 に答える