SQL硬编码数据透视

时间:2018-06-05 13:45:59

标签: sql sql-server sql-server-2008 pivot

我有一些发票税收分析"垂直"我需要" pivot"他们。 我正在使用SQL Server 2008R2

带代码的简化示例:

A"垂直"结果示例

15  9   NET     112.07  1/5156
15  9   VAT9    17.93   1/5156
26  18  NET     4.29    1/5157
26  18  VAT18   1.38    1/5157

重新创建它的代码:

CREATE TABLE #dummy
(department_id      numeric(10,0),
 vat_category_id    numeric(10,0),
 amount_category    char(5),
 amount             numeric(10,2),
 invoice_no         char(10))

INSERT #yy VALUES(15,   9,  'NET',  112.07, '1/5156')
INSERT #yy VALUES(15,   9,  'VAT9', 17.93,  '1/5156')
INSERT #yy VALUES(26,   18, 'NET',  4.29,   '1/5157')
INSERT #yy VALUES(26,   18, 'VAT18',1.38,   '1/5157')

应如何分解:

CREATE TABLE #pivot
(department_id              numeric(10,0),
 net_amount                 numeric(10,0),
 vat_category_id9_amount    numeric(10,2),
 vat_category_id18_amount   numeric(10,2),
 gross_amount               numeric(10,2))

请求结果的示例:

1/5156  112.07      17.93       null    130
1/5157  4.29        null        1.38    5,67

任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:4)

您可以使用conditional聚合:

select invoice_no,
       sum(case when amount_category = 'NET' then amount else 0 end),
       sum(case when amount_category = 'VAT9' then amount else 0 end),
       sum(case when amount_category = 'VAT18' then amount else 0 end),
       sum(amount)
from #dummy d
group by invoice_no;