我不是SQL的专家,我真的在努力解决这个问题(在SQL Server Management Studio中构建):
我的数据:
id_module id_cr
---------------------
001 12345
001 67891
001 12345
001 25896
002 23456
003 78912
003 23456
004 34567
004 34567
004 34567
004 89123
004 34567
004 34567
004 89123
004 89123
004 66663
我希望它看起来像 - 显示每个模块的前2个内容(按有多少个条目):
Grouped by id_module Grouped by id_cr Count (sum) of id_cr
001 12345 2
001 67891 1
002 23456 1
003 78912 1
003 23456 1
004 34567 5
004 89123 3
到目前为止,我有:
SELECT
id_module, id_cr,
RANK() OVER (PARTITION BY id_module ORDER BY id_module) AS 'Ranking',
COUNT(*) OVER (PARTITION BY id_cr) AS webtrackerCount
FROM
webtracker_user
WHERE
id_module > 0 AND id_cr > 0
ORDER BY
id_module, webtrackerCount DESC
这给了我所有模块,每个id_cr列在他们自己的行上而不是分组。
示例:
id_module id_cr ranking webtrackerCount
-----------------------------------------------------
001 64639 1 32
001 64639 1 32
(this is repeated 30 more times)
001 38099 1 12
(this is repeated 11 more times)
002 84562 1 50
(this is repeated 49 more times)
etc.
那么,我有多远?有没有办法像我需要的那样做报告?任何帮助将非常感谢:)谢谢!
答案 0 :(得分:1)
在这里,我对您提供的查询进行了一些修改
QUERY 1
SELECT ID_MODULE, ID_CR
FROM (SELECT DISTINCT id_module,id_cr,
Rank() OVER (Partition by id_module Order by id_module, id_cr ) AS 'Ranking',
FROM webtracker_user ) a
WHERE a.Ranking <= 2
Order by ID_MODULE
我希望这对你有用,让我们知道它是怎么回事
或者您也可以让CTE对记录进行分组,然后进行一些排名,然后按以下方式过滤首选排名
QUERY 2
WITH CTE AS(
SELECT *, Rank() OVER (Partition by id_module Order by id_module, id_cr ) AS 'Ranking'
FROM (SELECT DISTINCT id_module,id_cr
FROM webtracker_user) a
)
SELECT ID_MODULE, ID_CR
FROM CTE a
WHERE a.Ranking <= 2
Order by ID_MODULE