Aggregate Query返回多个记录

时间:2012-08-30 15:57:30

标签: sql tsql aggregation

我有下表(简化):

RecordID       bigint         IDENTITY
ItemID         bigint
ConfigID       varchar
Status         varchar
StatusDate     date

示例数据

001  04  1E  10    2007-08-14 13:57:54
002  04  1E  12    2007-08-21 16:10:21
003  04  1D  10    2007-09-27 17:14:13
004  04  1D  43    2011-01-10 13:44:50
005  04  1B  50    2008-06-20 09:09:51
006  05  1A  17    2007-12-18 14:04:56
007  05  1A  11    2007-10-17 08:23:52
008  05  1A  12    2007-10-19 12:54:18
009  05  1B  12    2007-11-02 09:23:54
010  05  1B  40    2010-06-17 09:34:33
011  07  1A  12    2007-11-19 14:48:06
012  07  1A  12    2007-11-19 15:02:48
013  07  1B  40    2011-01-10 14:36:16
014  08  1B  10    2009-05-22 11:14:42
015  08  1B  12    2007-11-20 17:02:44
016  08  1A  12    2007-12-12 16:11:57
017  08  1A  10    2009-11-12 11:12:45
018  08  1C  35    2011-01-10 18:30:10
019  08  1D  12    2009-10-14 14:34:47
020  08  1D  10    2009-10-14 14:35:09

这就是我的问题:

我需要能够让最终用户查询此数据以返回记录,这些记录将显示itemid和config的每个唯一组合的最新状态和状态。因此,使用上面的示例我想返回一个匹配以下内容的记录集:

002  04  1E  12    2007-08-21 16:10:21
004  04  1D  43    2011-01-10 13:44:50
005  04  1B  50    2008-06-20 09:09:51
006  05  1A  17    2007-12-18 14:04:56
010  05  1B  40    2010-06-17 09:34:33
012  07  1A  12    2007-11-19 15:02:48
013  07  1B  40    2011-01-10 14:36:16
017  08  1A  10    2009-11-12 11:12:45
018  08  1C  35    2011-01-10 18:30:10
020  08  1D  10    2009-10-14 14:35:09

用简单的英语:我需要能够返回每个项目配置的最新状态和状态日期。

非常感谢这方面的任何帮助。提前谢谢。

3 个答案:

答案 0 :(得分:4)

您可以在子查询中执行GROUP BY子句。尝试,

SELECT  a.*
FROM    yourtable a 
        INNER JOIN
        (
            SELECT      ItemID, ConfigID, MAX([StatusDate]) maxStat
            FROM        yourtable
            GROUP BY    ItemID,ConfigID
        ) b on a.configID = b.configID AND
                a.[statusDate] = b.MaxStat AND
                a.ItemID = b.ItemID
Order by RecordID

SQLFiddle Demo

答案 1 :(得分:3)

SELECT
    RecordID,
    ItemID,
    ConfigID,
    Status,
    StatusDate
FROM
    (SELECT
        RecordID,
        ItemID,
        ConfigID,
        Status,
        StatusDate,
        ROW_NUMBER() OVER(PARTITION BY ItemId,ConfigID ORDER BY StatusDate DESC) As StatusOrder
    FROM
        MyTable) Statuses
WHERE
    StatusOrder= 1

答案 2 :(得分:3)

在SQL Server 2005+中,您可以使用CTE:

;with cte as
(
  select recordid,
    itemid,
    configid,
    status,
    statusdate,
    row_number() over(partition by itemid, configid
                        order by statusdate desc) rn
  from yourtable
)
select *
from cte
where rn = 1
order by recordid

请参阅SQL Fiddle with Demo