一尘不染

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

sql-server

我有一个像这样的子表:

[客户日期表]

| 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; 

问题是这不只为每个客户返回一行——它返回多行。


阅读 90

收藏
2022-11-23

共1个答案

一尘不染

你只是想要:

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;
2022-11-23