SQL 根据If 条件在other table 中插入两行

SQL Insert two rows in other table based on If confition

我有 2 个 table,分别是 DATA 和 MAIN。 DATA table 是从 excel 中提取的原始数据,而 MAIN table 是经过验证(很少规则)后的数据。

规则:

  1. 如果金额 1<>'' 和金额 2<>''。 在 MAIN table 中插入 2 行。第一行的金额和百分比值来自 Amount2 和 Percentage2,TaxRateType = Taxable。 第二行将有从 Amount1 和 Percentage1 获得的金额和百分比,TaxRateType = EXEMPT。 invoiceNo 也将添加 '_1'
  2. 如果金额 2<>'' 和金额 1='' 使用 TaxRateType = Taxable 从 Amount2 和 Percentage2 中插入 Amount 和 Percentage 的 1 行。
  3. 其他 插入 1 行,其中 Amount 和 Percentage 从 Amount1 & Percentage1 获得,TaxRateType = EXEMPT

例子如下table:

**DATA**
InvoiceNo | TotalAmount | Percentage1 | Amount1 | Percentage2 | Amount2 
abc123         100             5           45          20          55
abc124          60             5           60          20
abc125          50             5                       22          50

**MAIN**
InvoiceNo | Percentage | Amount | TaxRateType | ReferenceValue
abc123          20         55      TAXABLE            2
abc123_1         5         45       EXEMPT            1
abc124           5         60       EXEMPT            1
abc125          22         50      TAXABLE            2

我在这里困了 4 个小时来寻找使用哪种方法。目前我有一个使用 if exists 的想法,但它仍然不正确,不知何故我觉得它不是一个好方法。

IF EXISTS (SELECT ID from [alcatel].[Main_Temp] where Amount0<>'' and Amount21<>'')
BEGIN
INSERT INTO [alcatel].[Main] 
    ( [Country],[InvoiceNo],[Amount],[Percentage],[TaxRateType],[Reference Value])
SELECT 
    [Country],[InvoiceNo],[Amount2],[Percentage2],'TAXABLE' as [TaxRateType],2 as [Reference Value]
FROM [alcatel].[Data];

INSERT INTO [alcatel].[Main] 
    ( [Country],[InvoiceNo],[Amount],[Percentage],[TaxRateType],[Reference Value])
SELECT 
    [Country],[InvoiceNo]+'_1' as InvoiceNo,[Amount1],[Percentage1],'EXEMPT' as [TaxRateType],'1' as [Reference Value]
FROM [alcatel].[Data];
END
Followed with other condition.

我想你只是想用一些逻辑来逆透视数据:

select invoiceno + v.suffix, v.percentage, v.amount,
       v.taxratetype, v.referencevalue
from data d cross apply
     (values (1, d.Percentage1, d.Amount1, 'EXEMPT', ''),
             (2, d.Percentage2, d.Amount2, 'TAXABLE', (case when d.amount1 is not null then '_1' else '' end))
     ) v(ReferenceValue, Percentage, Amount, TaxRateType, Suffix)
where amount is not null;

Here 是一个 db<>fiddle.