LoginSignup
1
0

More than 3 years have passed since last update.

【SQL】結合したテーブルを基に、複数レコードをテーブルに挿入する(ROW_NUMBER))

Last updated at Posted at 2019-08-21

結合したテーブルの複数レコードを、別テーブルに挿入する方法

売上表を時系列データを持つ売上明細表と結合させ、8月の売上表レコードを抽出して別テーブルに挿入
INSERT INTO August_SalesDetails(Id,SalesId,ProductId,Quantity,UnitPrice,Price,Note)

/*SELECTで抽出した表が挿入される*/
SELECT
ROW_NUMBER() over(order by D.id) +  (select max(Id) from SalesDetails)
,D.SalesId
,D.ProductId
,D.Quantity
,D.UnitPrice
,D.Price
,D.Note

/*以下で表を結合。8月の売上データ表を生成*/
FROM
SalesDetails D
join
Sales Sa
On D.SalesId = Sa.Id
Where MONTH(Sa.SalesAt) = 8 and YEAR(Sa.SalesAt) = 2019  

主要キーであるIdカラムには抽出したフィールドを挿入することができないので、ROWNUMBER()を使って、順番にIdを振り直す。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0