SQL select top counts for grouped rows

I have a table with the inscriptions and next to them:

id  |  label  |  code
1   |  foo    |  21
2   |  foo    |  33
3   |  foo    |  33
4   |  foo    |  13
5   |  foo    |  13
6   |  foo    |  33
7   |  bar    |  13
8   |  bar    |  13
9   |  bar    |  33
10  |  smt    |  33
11  |  smt    |  13

I need a query that selects the high frequencies of the "code" for each "tag". Here is what I still have:

SELECT count(*) frequency, label, code
FROM myTable
GROUP BY label, code

This gives me:

frequency | label | code
1         | foo   | 21
3         | foo   | 33
2         | foo   | 13
2         | bar   | 13
1         | bar   | 33
1         | smt   | 33
1         | smt   | 13

I would like to:

frequency | label | code
3         | foo   | 33
2         | bar   | 13
1         | smt   | 33
1         | smt   | 13

As you can see, for "foo" and "bar" only the high frequencies are selected. Since "smt" does not have a maximum frequency as such (all are the same), all lines are included.
I have no idea, even where to start. Can anybody help? Thank you (By the way, I'm using mssql)

+4
source share
4 answers

My similar solution like @TechDo, but with 1 subquery

SELECT frequency,label,code FROM
(
  SELECT
    count(*) AS frequency
    ,MAX(COUNT(*)) OVER (PARTITION BY label) AS Rnk
    ,label
    ,code
  FROM myTable
  GROUP BY label, code
) x
WHERE frequency=Rnk
ORDER BY frequency DESC

Sqlfiddle here

+2

:

SELECT * FROM(
    SELECT *, 
        MAX(frequency) OVER(PARTITION BY label) Col1
    FROM(
        SELECT count(*) frequency, label, code
        FROM myTable
        GROUP BY label, code
    )x
)xx 
WHERE frequency=Col1
+2

RANK():

SELECT frequency, label, code FROM
(
    SELECT frequency, label, code, RANK() OVER(PARTITION BY code ORDER BY frequency DESC) [rank]
    FROM (
        SELECT count(*) frequency, label, code
        FROM myTable
        GROUP BY label, code
    ) Counts
) Ranked
WHERE [rank] = 1
ORDER BY frequency DESC
0

,

with cte as
(SELECT count(*) frequency, label, code
FROM myTable
GROUP BY label, code
)
,cte1 as
(
Select *,ROW_NUMBER()over order(partition by label order by frequency)rn1
)

select * from cte1 where rn=1
-1

Source: https://habr.com/ru/post/1526914/


All Articles