SQL过程中嵌套排序数据的确切数目

时间:2019-05-28 07:05:01

标签: sql sql-server tsql

我有这样一个过程:

SELECT Name, Date, Par3, Date_rank
FROM
   (SELECT Name, ROW_NUMBER() OVER (PARTITION BY Date ORDER BY Par3 ASC) 
   AS Date_rank
   FROM Table
   WHERE (..conditions..)) ranked
WHERE Par2_rank <= 3
ORDER BY Par2 ASC, Par3 ASC

如果行数小于或等于3,则结果为我:

Name,    Date,     Par3,    Date_rank
AB   2010-01-01    1.5          1
CD   2010-02-16    0.9          1
EF   2010-02-16    1.1          2
GH   2010-02-16    1.7          3

但是我只需要结果,其中日期的确切行数等于3。 所以结果应该是:

Name,    Date,     Par3,    Date_rank
CD   2010-02-16    0.9          1
EF   2010-02-16    1.1          2
GH   2010-02-16    1.7          3

我试图放WHERE Par2_rank = 3

然后我只得到一行:

Name,    Date,     Par3,    Date_rank
GH   2010-02-16    1.7          3

我也尝试使用HAVING COUNT,但是没有行。

谢谢。

更新: 感谢大家的快速解答。 COUNT(*)OVER PARTITION可以解决问题。太简单了。.希望以后能有更好的SQL编码。

3 个答案:

答案 0 :(得分:5)

如果我正确理解了您的问题,请尝试使用带有SUM()子句的OVER,但不要使用ORDER BY的以下方法:

输入:

CREATE TABLE #Table (
    Name varchar(2),
    [Date] date,
    Par3 numeric(5, 1)
)
INSERT INTO #Table
    (Name, [Date], Par3)
VALUES
    ('AB', '20100101', 1.5),
    ('AB', '20100101', 1.6),
    ('AB', '20100102', 1.5),
    ('AC', '20100102', 1.6),
    ('AD', '20100102', 1.7),
    ('AE', '20100102', 1.8),
    ('CD', '20100216', 0.9),
    ('EF', '20100216', 1.1),
    ('GH', '20100216', 1.7)

T-SQL:

SELECT Name, [Date], Par3, Rn
FROM (
    SELECT 
        Name, 
        [Date], 
        Par3, 
        ROW_NUMBER() OVER (PARTITION BY [Date] ORDER BY Par3 ASC) AS Rn,
        COUNT(*) OVER (PARTITION BY [Date]) As Cnt
    FROM #Table
    ) ranked
WHERE Cnt = 3

输出:

------------------------------
Name    Date        Par3    Rn
------------------------------
CD      2010-02-16  0.9     1
EF      2010-02-16  1.1     2
GH      2010-02-16  1.7     3

答案 1 :(得分:2)

WITH cte_ranked
AS
(
 SELECT Name, [Date], Par3
       ,COUNT(*) OVER (PARTITION BY [Date]) As DateCount
 FROM Table
 )

SELECT Name, [Date], Par3
FROM cte_ranked
WHERE DateCount = 3
ORDER BY [Date], Par3

答案 2 :(得分:2)

您可以使用EXISTS做到这一点:

WITH ranked AS
(
    SELECT Name, date, ROW_NUMBER() OVER (PARTITION BY Date ORDER BY Par3 ASC) 
       AS Date_rank
       FROM Table
       WHERE (..conditions..)
) 
SELECT 
    *
FROM ranked AS R
    WHERE EXISTS (SELECT 1
                    FROM ranked
                    where r.Date = Date
                    and Date_rank = 3
                    and Date_rank <> 4
                  )