比较SQL列中的两个日期

时间:2013-04-15 15:56:34

标签: sql sql-server-2005

我在解决这个问题上遇到了一些问题。我有一张包含这些数据的表格。

|     DateStarted       |     Field9     |     Field2     |      ID      |    Field6   |
----------------------------------------------------------------------------------------
|  2013-04-15 09:23:00  |      TEST1     |      TEST2     |      1       |     2000    |
|  2013-04-08 09:23:00  |      TEST1     |      TEST2     |      2       |      180    |
|  2013-04-15 09:23:00  |      TEST2     |      TEST3     |      3       |     1000    |
|  2013-04-04 09:23:00  |      TEST2     |      TEST3     |      7       |       80    |
|  2013-04-03 09:23:00  |      TEST2     |      TEST4     |      5       |       70    |

我的最终目标是返回Field9的值的最后两个日期,以便我可以为Field9的每个唯一实例减去Field6的值。以下是退货的例子。

|     DateStarted       |     Field1     |     Field2     |      ID      |    SUB      |
----------------------------------------------------------------------------------------
|  2013-04-15 09:23:00  |      TEST1     |      TEST2     |      1       |     1820    |
|  2013-04-15 09:23:00  |      TEST2     |      TEST3     |      3       |      920    |

所以对于第二行,它花了两个最大的日期然后取了field6的值并减去它们只返回一行。

2 个答案:

答案 0 :(得分:2)

您可以使用分区窗口函数获取Field1的每个唯一值的最新行。

;WITH x AS
(
  SELECT DateStarted, Field9, Field2, ID, Field6,
   rn = ROW_NUMBER() OVER (PARTITION BY Field9 ORDER BY DateStarted DESC)
  FROM dbo.your_table_name
),
y AS 
(
  SELECT x.*, [SUB] = x.Field6 - COALESCE(y.Field6, 0)
  FROM x LEFT OUTER JOIN x AS y
  ON x.Field9 = y.Field9
  AND x.rn = 1 AND y.rn = 2
)
SELECT DateStarted, Field1 = Field9, Field2, ID, [SUB]
  FROM y
  WHERE rn = 1
  ORDER BY Field1;

SQL fiddle demo

答案 1 :(得分:0)

获得差异的一种方法是识别两行,然后将它们聚合在一起:

select MAX(case when seqnum = 1 then DateStarted end), Field1,
       max(case when seqnum = 1 then Field2 end) as Field2
       MAX(case when seqnum = 1 then id end) as Id,
       MAX(case when seqnum = 1 then field3 end) - MAX(case when seqnum = 2 then field 3 end) as sub
from (SELECT DateStarted, Field1, Field2, ID, Field3,
             ROW_NUMBER() OVER (PARTITION BY Field1 ORDER BY DateStarted DESC) as seqnum
      FROM t
     ) t
group by Field1

这使用条件聚合来获得差异。