我有以下查询:
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
但是必须有一种更简单,更有效的方法。有任何想法吗?
计算ROW_NUMBER后UNION。
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。
UNION ALL