1

我有下表(简化):

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 的每个唯一组合的最新状态和 statusdate。因此,使用上面的示例,我想返回与以下内容匹配的记录集:

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

简而言之:我需要能够返回每个项目配置的最新状态和状态日期。

在这方面的任何帮助将不胜感激。先感谢您。

4

3 回答 3

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 演示

于 2012-08-30T16:02:01.120 回答
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
于 2012-08-30T16:05:13.013 回答
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

于 2012-08-30T16:11:20.017 回答