根据最大日期返回包含多行的结果集


16

我有一个子表是这样的:

[客户日期表]

| Customer ID | Some Date  | Balance |
+-------------+------------+---------+
|           1 | 2012-04-30 |   20.00 |
|           1 | 2012-03-31 |   50.00 |
|           2 | 2012-04-30 |    0.00 |
|           2 | 2012-03-31 |   10.00 | 
|           3 | 2012-03-31 |   60.00 |
|           3 | 2012-02-29 |   10.00 |

我希望能够获得这样的结果集-每个客户的最新日期记录:

| Customer ID | Some Date  | Balance |
+-------------+------------+---------+
|           1 | 2012-04-30 |   20.00 | 
|           2 | 2012-04-30 |    0.00 |
|           3 | 2012-03-31 |   60.00 |

我知道我可以使用以下SQL(SQL Server语法)为每个“客户ID”执行此操作:

select top 1  [Some Date], [Customer ID], [Balance]
from [Cust Date Table]
where [Customer ID] = 2
order by [Some Date] desc


| Customer ID | Some Date  | Balance |
+-------------+------------+---------+
|           2 | 2012-04-30 |    0.00 |

但是我不确定如何获取我想要的所有三个记录。我不确定这是否是需要子查询或其他查询的情况。

请注意,任何给定的[Customer ID]的最大日期可以不同(在此示例中,客户3的最大日期为2012-03-31,而其他记录的最大日期为2012-04-30)。我试过了

select [Customer ID], MAX([Some Date]) AS [Latest Date], Balance 
from [Cust Date Table] 
group by [Customer ID], Balance; 

问题在于,这不仅会为每个客户返回一行,还会返回多行。

Answers:


18

您只想要:

SELECT
    [Customer ID],
    MAX([Some Date]) AS[Latest Date]
FROM[Cust Date TABLE]
GROUP BY
    [Customer ID];

好的-您已对其进行了修改。现在,您要对行进行排序并选择最上面的行:

WITH numbered AS (
    SELECT
        [Customer ID],
        [Some Date],
        [Balance],
        ROW_NUMBER() OVER (
            PARTITION BY
                [Customer ID]
            ORDER BY
                [Some Date] DESC
        ) AS rownum
    FROM[Cust Date TABLE]
)
SELECT
    [Customer ID],
    [Some Date],
    [Balance]
FROM numbered
WHERE
    rownum = 1;

哦-您更改了问题?
罗伯·法利

现在更改了我的答案。
罗布·法利

此解决方案的一个优点(或缺点,取决于您的要求)是,如果同一客户的最新日期出现在多行中,则不会产生重复的结果。
蒂姆(Tim)

7

我想你是在追求这样的事情

select c.[customer ID], [some date], balance
from [cust date table] c
inner join 
    ( select [customer ID], MAX([some date]) as maxdate
    from [cust date table]
    group by [customer ID]) c2
on c2.[customer ID] = c.[customer ID]
and c2.maxdate = c.[some date]

您可以尝试使用CTE,表变量,#table这样的多种变体,以查看在您所处的情况下能带来最佳性能的因素。


这个答案也是正确的。不幸的是,我没有足够的代表来推荐它,我必须选择一个答案。
2012年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.