4

私はこのような2つのテーブルを持っています:

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にグループ化された「シーケンス」値の両方を取得する値を3番目のテーブルに挿入する必要があります。これを試しましたが、シーケンスの値は常に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

私はおそらくここで愚かな単純なものを見逃していることを知っていますが、私は立ち往生しています。

4

1 に答える 1

4
insert into Table3 (Table2ID, Table1ID, Sequence)
select
  Table2ID,
  Table1ID,
  row_number() over(partition by Table1ID order by Table2ID)
from Table2

テストするもの:

declare @Table2 table
(
  Table2ID int identity,
  Table1ID int
)
insert into @Table2 values
(1),(1),
(2),
(3),(3),(3),
(4),(4)

declare @Table3 table
(
  Table2ID int, 
  Table1ID int, 
  Sequence int
)

insert into @Table3 (Table2ID, Table1ID, Sequence)
select
  Table2ID,
  Table1ID,
  row_number() over(partition by Table1ID order by Table2ID)
from @Table2

select *
from @Table3

結果:

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
于 2011-07-25T17:27:24.840 に答える