Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

tsql - Select from 2 rows in one table into a single row with 2 or more columns in the second table

I have a table that has 2 columns. One is a type column and the other is a value amount column. There are only 2 types/ I would like to select columns of this table into another table with 2 combined columns based on type and value. For example, the table may have order with 2 of the types in 2 rows. It would be inserted into the 2nd table as one row.

Example:

Table 1

| ID | OrderID | Type | Value | |:-----|:--------:|:------------:|-------:| | 1 | 300 | bike | 100 | | 2 | 300 | skateboard | 150 | | 3 | 700 | bike | 200 | | 4 | 700 | skateboard | 50 | | 5 | 800 | bike | 150 | | 6 | 800 | skateboard | 100 _ What is the TSQL to have it inserted into the 2nd table with these values? Table 2 | ID | OrderID | BikeValue | SkateboardValue | |:----|:--------:|:----------:|-----------------:| | 1 | 300 | 100 | 150 | | 2 | 700 | 200 | 50 | | 3 | 800 | 150 | 100 |

question from:https://stackoverflow.com/questions/65893182/select-from-2-rows-in-one-table-into-a-single-row-with-2-or-more-columns-in-the

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just make it simple for yourself. Do two SQL statements. One to insert and another to update.

INSERT INTO Table2 (OrderID, BikeValue)
SELECT Table1.OrderID, Table1.Value
FROM Table1 (NOLOCK) 
WHERE Table1.Type = 'bike'

UPDATE Table2 SET Table2.SkateboardValue = Table1.Value 
FROM Table2 
    INNER JOIN Table1 ON Table1.OrderID = Table2.OrderID 
WHERE Table1.Type = 'skateboard'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...