[英]SQL Hardcoded pivoting of data
I have some invoices tax analysis "vertically" and I need to "pivot" them. 我有一些“垂直”的发票税分析,我需要“转动”它们。 I am using SQL Server 2008R2 我正在使用SQL Server 2008R2
Simplified example with code: 带代码的简化示例:
A "vertical" results example “垂直”结果示例
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
Code to recreate it: 用于重新创建它的代码:
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')
How it should be broken down: 它应该如何分解:
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))
Sample example of the requested outcome: 请求结果的示例示例:
1/5156 112.07 17.93 null 130
1/5157 4.29 null 1.38 5,67
Any help appreciated! 任何帮助赞赏!
You can use conditional
aggregation : 您可以使用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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.