2013-03-06 90 views
1

我在这个形式的数据:逆透视税收数据

department_id | VAT_id | Tax_amount | Net_amount | Gross_amount | Date  | Invoice_no 
     1  | 3 | 10  | 90  | 100   | 20130101 | A5 
     1  | 8 | 5  | 35  | 40   | 20130101 | A5 
     3  | 3 | 5  | 45  | 50   | 20130101 | A8 

而且我希望把它改造成:

Department_id | Vat_id | Amount | Date  | Invoice_No 
1    | 3  | 10 | 20130101 | A5 
1    | 0  | 90 | 20130101 | A5 
1    | -1  | 100 | 20130101 | A5 
1    | 8  | 5  | 20130101 | A5 
1    | 0  | 35 | 20130101 | A5 
1    | -1  | 40 | 20130101 | A5 
3    | 3  | 5  | 20130101 | A8 
3    | 0  | 45 | 20130101 | A8 
3    | -1  | 50 | 20130101 | A8 

Vat_id 0值是净额

Vat_id值-1是总金额。

我如何verticalize这个数据让我能继续前进?

+2

为 'verticalize' 公共技术术语是 '折',有时 '逆透视'。 – 2013-03-06 17:24:16

+0

thanx很多Pieter – PanosPlat 2013-03-07 07:13:04

回答

3

可以使用UNPIVOT函数来执行此:

select department_id, 
    case 
    when col = 'net_amount' then 0 
    when col = 'Gross_amount' then -1 
    else vat_id end vat_od, 
    amount, 
    invoice_no 
from yourtable 
unpivot 
(
    amount 
    for col in ([Tax_amount], [Net_amount], [Gross_amount]) 
) unpiv 

SQL Fiddle with Demo

如果你没有进入逆透视功能,那么你可以使用一个UNION ALL查询。

select department_id, 
    case 
    when col = 'net_amount' then 0 
    when col = 'Gross_amount' then -1 
    else vat_id end vat_od, 
    amount, 
    invoice_no 
from 
(
    select department_id, vat_id, 
    'tax_amount' col, tax_amount amount, invoice_no 
    from yourtable 
    union all 
    select department_id, vat_id, 
    'Net_amount' col, Net_amount amount, invoice_no 
    from yourtable 
    union all 
    select department_id, vat_id, 
    'Gross_amount' col, Gross_amount amount, invoice_no 
    from yourtable 
) src 

SQL Fiddle with Demo

两个查询将返回:

| DEPARTMENT_ID | VAT_OD | AMOUNT | INVOICE_NO | 
------------------------------------------------ 
|    1 |  3 |  10 |   A5 | 
|    1 |  0 |  90 |   A5 | 
|    1 |  -1 | 100 |   A5 | 
|    1 |  8 |  5 |   A5 | 
|    1 |  0 |  35 |   A5 | 
|    1 |  -1 |  40 |   A5 | 
|    3 |  3 |  5 |   A8 | 
|    3 |  0 |  45 |   A8 | 
|    3 |  -1 |  50 |   A8 | 
+0

Suberb!优雅!谢谢! – PanosPlat 2013-03-07 07:12:29