簡體   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