gpt4 book ai didi

SQL 硬编码数据透视

转载 作者:行者123 更新时间:2023-12-04 22:18:22 24 4
gpt4 key购买 nike

我有一些“垂直”发票税务分析,我需要“旋转”它们。我正在使用 SQL Server 2008R2

带代码的简化示例:

“垂直”结果示例

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

感谢任何帮助!

最佳答案

您可以使用条件聚合:

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;

关于SQL 硬编码数据透视,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50701718/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com