我有两个这样的表:
Table1ID Table2ID Table1ID SomeDate
-------- ------------------------------
1 1 1 2011-01-01
2 2 1 2011-01-02
3 3 2 2011-01-01
4 4 3 2011-01-01
5 3 2011-01-02
6 3 2011-01-03
7 4 2011-01-01
8 4 2011-01-02
我需要将值插入到第三个表中,该表给我来自 Table2 的两个值,以及在 Table1ID 上分组的“序列”值。我试过这个,但我总是得到 1 的序列值。
;WITH Sequences AS (
SELECT t1.Table1ID,
MAX(ISNULL(t3.Sequence, 0)) AS [MaxSequence]
FROM Table1 t1
LEFT JOIN Table3 t3 (NOLOCK) ON t1.Table1ID = t3.Table1ID
GROUP BY t1.Table1ID
)
INSERT INTO Table3 ( Table1ID, Table2ID, Sequence )
SELECT t1.Table1ID,
t2.Table2ID,
s.MaxSequence + 1
FROM Table1 t1 (NOLOCK)
JOIN Table2 t2 (NOLOCK) ON t1.Table1ID = t2.Table2ID
JOIN Sequences s ON t2.Table1ID = s.Table1ID
ORDER BY t2.SomeDate
我想要的是这样的结果集:
Table2ID Table1ID Sequence
------------------------------
1 1 1
2 1 2
3 2 1
4 3 1
5 3 2
6 3 3
7 4 1
8 4 2
我知道我可能在这里遗漏了一些愚蠢简单的东西,但我被困住了。