1

我在让它工作时遇到了一些问题。我有一张表,里面有这些数据。

|     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 的值并减去它们,只返回一行。

4

2 回答 2

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小提琴演示

于 2013-04-15T15:58:30.163 回答
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

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

于 2013-04-15T16:06:04.383 回答