我一直试图在这里适应其他答案多年没有成功,所以这里......我有一个基本的问题:
SELECT
*
FROM
@tbl_counts
ORDER BY
sgId,
CategoryCount DESC,
qccId;
这显示以下结果:
sgId qccId CategoryCount
------- -------- -------------
4668 18 8
4668 77 7
4668 2 6
4669 43 2
4669 46 2
4670 25 3
4670 27 3
4670 74 2
4671 56 4
4671 60 3
4671 74 3
4671 54 3
4671 55 3
4671 78 2
4671 88 1
4671 89 1
4671 90 3
我需要修改此查询以显示以下内容:
对于每个唯一的sgId
值,显示前3个CategoryCount
值(如果存在,则显示关联)以及相应的qccId
值。因此,结果应该是:
sgId qccId CategoryCount
------- ----- -------------
4668 18 8
4668 77 7
4668 2 6 -- top 3 4668
4669 43 2
4669 46 2 -- top 2 4669 because only 2 existed
4670 25 3
4670 27 3
4670 74 2 -- top 3 4670
4671 56 4
4671 60 3
4671 74 3
4671 54 3
4671 55 3 -- top 5 4671 caused by TIES, but discards others
通常我会在这里ROW_NUMBER,但我正在努力,因为它没有提出TIES(我不认为)。因此,在调整我发现的其他答案时,我已经做到这一点,但它没有正常工作......
SELECT
cnt.*
FROM
(
SELECT DISTINCT
sgId
FROM
@tbl_counts) sg INNER JOIN
(
SELECT TOP 3 WITH TIES
*
FROM
@tbl_counts
ORDER BY
CategoryCount DESC) cnt ON cnt.sgId = sg.sgId
答案 0 :(得分:2)
看起来像窗函数ProductBuildVersion = 13E238;
ProductCopyright = "1983-2016 Apple Inc.";
ProductName = "iPhone OS";
ProductVersion = "9.3.1";
的完美工作:
DENSE_RANK
答案 1 :(得分:0)
您可以使用标题中提议的TOP 1 WITH TIES
:
SELECT TOP 1 WITH TIES *
FROM @tbl_counts
ORDER BY
IIF(DENSE_RANK() OVER(PARTITION BY sgId ORDER BY CategoryCount DESC)<=3,0,1);
的 LiveDemo
强>