如何从group by子句中获取表键ID

时间:2014-06-20 17:51:37

标签: sql sql-server-2008-r2

我有以下查询:

SELECT ppa.Policy_ID
, (SELECT MAX(ppa2.Deactivated_Date) FROM Policy_Postage_Account ppa2 
         WHERE ppa.Policy_ID = ppa2.Policy_ID) AS maxDate
FROM Policy_Postage_Account AS ppa
WHERE ppa.Active = 0 
GROUP BY ppa.Policy_ID
ORDER BY maxDate

并返回以下内容:

Policy_ID   maxDate
6416        2014-06-19 11:14:50.890
3428        2014-06-19 11:17:55.760
8127        2014-06-19 12:02:06.223
8115        2014-06-19 12:02:56.223
7651        2014-06-20 09:31:30.193

这是我需要的大部分信息,但我还需要此表中的id列。因此,如果主键列是Policy_Post_ID为INT,我需要以下结果:

Policy_ID   maxDate                       Policy_Post_ID
6416        2014-06-19 11:14:50.890       2
3428        2014-06-19 11:17:55.760       5
8127        2014-06-19 12:02:06.223       66
8115        2014-06-19 12:02:56.223       567
7651        2014-06-20 09:31:30.193       9

提前致谢

2 个答案:

答案 0 :(得分:2)

我假设这些列位于单个表中,并且包含多个停用日期。

;WITH CTE AS (
    SELECT
        ROW_NUMBER() OVER (PARTITION BY Policy_ID ORDER BY Deactivated_Date DESC) ID
        , Policy_Post_ID
        , Policy_ID
        , Deactivated_Date
    FROM Policy_Postage_Account
    WHERE ppa.Active = 0
)
SELECT
    Policy_Post_ID
    , Policy_ID
    , Deactivated_Date
FROM CTE
WHERE ID = 1

答案 1 :(得分:0)

对于现有查询,您不需要子查询来获取这些结果。以下查询应返回相同的结果:

SELECT ppa.Policy_ID, MAX(ppa.Deactivated_Date) as maxDate
FROM Policy_Postage_Account AS ppa
WHERE ppa.Active = 0 
GROUP BY ppa.Policy_ID
ORDER BY maxDate

现在,为了获取Policy_Post_ID的值,您可以将上述查询作为临时表包含在内,并使用Policy_ID(我假设这是您的主键)来查找Policy_Post_ID。

SELECT temp.Policy_ID, temp.maxDate, PPA1.Policy_Post_ID from
(SELECT ppa.Policy_ID, MAX(ppa.Deactivated_Date) as maxDate
FROM Policy_Postage_Account AS ppa
WHERE ppa.Active = 0 
GROUP BY ppa.Policy_ID
ORDER BY maxDate) temp 
left join Policy_Postage_Account PPA1
on temp.Policy_ID = PPA1.Policy_ID