简体   繁体   English

用于将sinlge行从一个表插入另一个表中的多个行的SQL查询

[英]SQL query to insert sinlge row from one table into multiple rows in another table

I have table table_1: 我有桌子table_1:

PID DIV1 DES1 DIV2 DES2 DIV3 DES3  DIV4  DES4 DIV5  DES5
1    D1   DS1 D2  DS2    D3   DS3  null  null D5    null

output 产量

table_2: TABLE_2:

TID PID DIV DES
001  1   D1  DS1
002  1   D2  DS2
003  1   D3  DS3
004  1   D5  null

I need to right an insert statement to insert from table_1 to table_2. 我需要将insert语句从table_1插入到table_2。 If table has null values on both DIV and DES then i should not insert those fields. 如果表在DIV和DES上都有空值,那么我不应该插入这些字段。

Thank you 谢谢

In SQL Server, you can use 在SQL Server中,您可以使用

WITH a(PID, DIV, DES, NO) as (
    SELECT PID, DIV1, DES1, 1 FROM table_1 WHERE DIV1 IS NOT NULL OR DES1 IS NOT NULL
    UNION ALL
    SELECT PID, DIV2, DES2, 2 FROM table_1 WHERE DIV2 IS NOT NULL OR DES2 IS NOT NULL
    UNION ALL
    SELECT PID, DIV3, DES3, 3 FROM table_1 WHERE DIV3 IS NOT NULL OR DES3 IS NOT NULL
    UNION ALL
    SELECT PID, DIV4, DES4, 4 FROM table_1 WHERE DIV4 IS NOT NULL OR DES4 IS NOT NULL
)
INSERT INTO table_2(TID, PID, DIV, DES)
SELECT ROW_NUMBER() OVER(order by PID, NO), PID, DIV, DES FROM a

In MySQL, you would change this to 在MySQL中,您可以将其更改为

INSERT INTO table_2(TID, PID, DIV, DES)
SELECT @i := @i + 1, PID, DIV, DES
  FROM (
    SELECT PID, DIV1 as DIV, DES1 as DES, 1 as NO FROM table_1 WHERE DIV1 IS NOT NULL OR DES1 IS NOT NULL
    UNION ALL
    SELECT PID, DIV2, DES2, 2 FROM table_1 WHERE DIV2 IS NOT NULL OR DES2 IS NOT NULL
    UNION ALL
    SELECT PID, DIV3, DES3, 3 FROM table_1 WHERE DIV3 IS NOT NULL OR DES3 IS NOT NULL
    UNION ALL
    SELECT PID, DIV4, DES4, 4 FROM table_1 WHERE DIV4 IS NOT NULL OR DES4 IS NOT NULL
   ) AS a,
   (select @i := 0) AS temp
order by PID, NO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从A表中的一行中多次选择,并将结果作为B表中的多行插入,并在一个查询中重复 - Multiple select from one row from A table and insert result as multiple rows in B table and repeat in one query SQL 在另一个表的多行中找到 id 时查询只返回一行 - SQL Query to return only one row when id is found in multiple rows from another table 将表中的许多行插入另一表中的唯一行 - Insert many rows from a table into one unique row in another table MySQL查询-一个表中的单行,另一表中的多行 - MySQL query - single row in one table with multiple rows in another table sql select查询一个表中的一行,而另一表中的多行 - sql select query for one row in one table and multiple row from another table 如何将多行作为一行插入到Mysql中的另一张表 - How to Insert multiple rows as one row to another table in Mysql SQL-将一个表中多列的两行匹配到另一表中的1行。 - SQL - Matching two rows from multiple columns in one table to 1 row in another table. SQL从表1中选择一行加入表2中的多行 - SQL select one row from table 1 joining on multiple rows in table 2 SQL query INSERT SELECT COUNT 从一个表逐行到另一个表 - SQL query INSERT SELECT COUNT from one table to another row by row SQL查询从一个表中选择不在另一表中的行 - SQL query to select row from one table which is not in another table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM