简体   繁体   中英

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

Table 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

Table 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:

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 :

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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