繁体   English   中英

为另一个表中的每一行插入多行

[英]Insert multiple rows for each row in another table

我正在寻找一个 SQL 查询,它为表 A 中的每一行将多行数据插入表 B

表 A

ID       BillNo       TAX       Amount      TotalAmount 
-------------------------------------------------------
1        001           5        100          105
2        002           20       400          420

我需要像这种格式一样将数据插入表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

我试过这个

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

但它首先插入所有“销售”行,然后是“现金”,然后是“税”。 我没有把它放在一组中。 像这样:

1    Sales       001        100
2    sales       002        400
3    Cash        001        105
4    Cash        002        420
5    Tax         001          5
6    Tax         002         20

请帮我解决。

你能测试一下这个 sql:

INSERT INTO `tableB` (`Type`, `Billno`, `Amount`)
SELECT 'Sales', `billno`, `Amount` 
FROM `TableA` 

你是什么意思“得到它在一个集合”? 您想按顺序插入吗? 然后你可以做这样的事情:

将查询与联合链接在一起并对其进行排序

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]

可能是您提出这样的查询:

    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)

我会使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM