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

我怎样才能垂直化这些数据,以便我可以继续前进?

4

1 回答 1

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

两个查询都将返回:

| 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 |
于 2013-03-06T17:13:12.057 回答