1

我是 sql server 的新手,我有以下包含一千多行的表结构。但出于举例目的,这就是它的样子

表导入

+------+---------+------------+------------+------------+------------+------------+
| Name |  Code   | SocksTotal | GlovesTotal| JeansTotal | ShirtsTotal| shoesTotal |
+------+---------+------------+------------+------------+------------+------------+
| OT   |   45612 |          2 |          1 |          0 |          1 |          4 | 
| OT   |    1234 |          0 |          1 |          0 |          0 |          0 | 
| US   |    45896|          0 |          0 |          0 |          0 |          0 | 
+------+---------+------------+------------+------------+------------+------------+

然后是第二个名为 Items 的表

+------+---------+
| ID   |  Item   | 
+------+---------+
| 1    |   socks |
| 2    |   Gloves|
| 3    |   Jeans |
| 4    |   Shirts|
| 5    |   shoes |
+------+---------+

从上面的表中,我需要编写一个脚本,该脚本将插入到另一个名为 ImportItems_Summary 的表中。预期的输出是

+------+---------+------------+------------+
| Id   |  Code   | Items_id   |Import_total|
+------+---------+------------+------------+
| 1    |   45612 |          1 |          2 |
| 2    |   45612 |          2 |          1 |
| 3    |   45612 |          4 |          1 |
| 4    |   45612 |          5 |          4 |
| 5    |   1234  |          2 |          1 |
+------+---------+------------+------------+

正如您在此处看到的,代码 45612 现在在 ImportItems_summary 表中有 4 个条目,其中项目不等于 0,并且 Items_id 链接到 Items 表 ID 列。

我怎样才能实现上述输出?..我阅读并看到一个游标可能会有所帮助,但我不确定如何实现这一点

4

1 回答 1

0

一种方法用于cross apply将非规范化表的列还原为行,然后将 items 表带上 a join,最后插入目标表:

insert into ImportItems_Summary (code, items_id, import_total)
select im.code, it.items_id, x.import_total
from import im
cross apply (values 
    ('socks',  sockstotal),
    ('gloves', glovestotal),
    ('jeans',  jeanstotal),
    ('shirts', shirtstotal),
    ('shoes',  shoestotal)
) x(item, import_total)
inner join items it on it.item = x.item
于 2020-10-28T16:26:43.787 回答