我有以下查询:
INSERT into @TEST (col1,staffnumber,rn)
SELECT starttime as col1,staffnumber,ROW_NUMBER() OVER (PARTITION BY StaffNumber ORDER BY STARTTIME DESC) AS rn
FROM @TempTable2 t2
UNION
SELECT eventdate as col1, staffnumber,ROW_NUMBER() OVER (PARTITION BY StaffNumber ORDER BY EVENTDATE DESC) AS rn
FROM @TempTable1 t1
但是,显然,这给了我以下值:
COL1 | staffnumber | rn
10/02/2014 10:29:24 1 1
10/02/2014 09:08:19 1 3
10/02/2014 10:00:23 1 2
10/02/2014 10:00:29 1 1
然而,我需要它来表明:
COL1 | staffnumber | rn
10/02/2014 10:29:24 1 1
10/02/2014 09:08:19 1 4
10/02/2014 10:00:23 1 3
10/02/2014 10:00:29 1 2
我可以通过执行以下操作来完成此操作:
INSERT into @TEST1 (col1,staffnumber,rn)
SELECT convert(time,col1),staffnumber,ROW_NUMBER() OVER (PARTITION BY StaffNumber ORDER BY convert(time,COL1) DESC) AS rn
FROM @TEST
但必须有一种更简单有效的方法。有什么想法吗?
答案 0 :(得分:4)
在ROW_NUMBER
之后计算UNION
。
SELECT *, ROW_NUMBER() OVER (PARTITION BY StaffNumber ORDER BY STARTTIME DESC) AS rn
FROM (
SELECT * FROM T1
UNION ALL
SELECT * FROM T2
) x
我怀疑你需要UNION ALL
。