不显示税收数据

时间:2013-03-06 17:07:55

标签: sql sql-server sql-server-2005 ssis unpivot

我有这种形式的数据:

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表示总金额。

如何对这些数据进行垂直化,以便我能继续前进?

1 个答案:

答案 0 :(得分: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

如果您无权访问unpivot功能,则可以使用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 |