[英]Insert multiple rows for each row in another table
I'm looking for a SQL query that inserts multiple rows of data into Table B for each row in Table A我正在寻找一个 SQL 查询,它为表 A 中的每一行将多行数据插入表 B
Table A表 A
ID BillNo TAX Amount TotalAmount
-------------------------------------------------------
1 001 5 100 105
2 002 20 400 420
And I need the data to be inserted in table B like this format我需要像这种格式一样将数据插入表B
Table B表 B
ID Type Billno Amount
-----------------------------------
1 Sales 001 100
2 Cash 001 105
3 Tax 001 5
4 sales 002 400
5 Cash 002 420
6 Tax 002 20
I tried this我试过这个
insert into tableB
select 'Sales', billno, Amount
from TableA
insert into tableB
select 'Cash', billno, TotalAmount
from TableA
insert into tableB
select 'Tax', billno, tax
from TableA
But it inserts first all rows of 'sales' then 'cash' then 'Tax'.但它首先插入所有“销售”行,然后是“现金”,然后是“税”。 I'm not getting it in a set.
我没有把它放在一组中。 Like this:
像这样:
1 Sales 001 100
2 sales 002 400
3 Cash 001 105
4 Cash 002 420
5 Tax 001 5
6 Tax 002 20
Please help me with a solution.请帮我解决。
Can you test this sql:你能测试一下这个 sql:
INSERT INTO `tableB` (`Type`, `Billno`, `Amount`)
SELECT 'Sales', `billno`, `Amount`
FROM `TableA`
What do you mean with "getting it in a set"?你是什么意思“得到它在一个集合”? Would you like to insert it in a ordered way?
您想按顺序插入吗? Then you can do something like this:
然后你可以做这样的事情:
chain the queries together with a union and sort it将查询与联合链接在一起并对其进行排序
insert into tableB ([Type], BillNo, AMount)
select 'sales' as [Type], BillNo, amount as AMount from TableA union
select 'cash' as [Type], BillNo, TotalAmount as AMount from TableA union
select 'tax' as [Type], BillNo, tax as AMount from TableA
order by BillNo, [Type]
May be you ment such query:可能是您提出这样的查询:
select t.Type, billno,
case t.Type
when 'Sales' then Amount
when 'Cash' then TotalAmount
when 'Tax' then tax
end as Amount
from TableA
cross join (values ('Sales'), ('Cash'), ('Tax')) as t(Type)
I would use apply
:我会使用
apply
:
insert into tableB (Type, BillNo, AMount)
select tt.type, t.billno, tt.amount
from table t cross apply
( values ('sales', t.Amount),
('cash', t.TotalAmount),
('Tax', t.tax)
) tt(type, amount)
order by t.billno;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.