SQL 行列转换

SQL 行列转换,第1张

前段时间有人问了一个问题,就是SQL的行列转换,当时有点懵没答上来,后来细细想一想,其实最近的一个项目就已经用到了。

基础数据如下:

要求根据当年的月份去统计出每一个ID的汇总金额。就是把行中的月切换到列中。

最后效果如下:

参考资料: https://technet.microsoft.com/zh-cn/library/ms177410(v=sql.105).aspx#%E5%A4%8D%E6%9D%82%20PIVOT%20%E7%A4%BA%E4%BE%8B

带批注的 PIVOT 语法。

如果聚合函数与 PIVOT 一起使用,则计算聚合时将不考虑出现在值列中的任何空值。

新建两张表

查询结果

--UNPIVOT 函数

--单纯用SQL 处理 ,原理很简单,就是对每个需要置换的列单独处理出来

最终效果:

--用上面的结果新建表

--PIVOT

-- SQL直接处理,先用CASE 语句将每行处理出来,然后在用聚合去处理合并相同ID的行。

create table rotatetable1 (序号 int,company char(66),box_weight char(12),废塑料numeric(10,2)),废五金 numeric(10,2)),废钢铁 numeric(10,2)),废纸 numeric(10,2)),废有色 numeric(10,2)),废纤维 numeric(10,2)),其它 numeric(10,2)),合计 numeric(10,2)))

insert into rotatetable1(company,box_weight) select name ,'weight' from sum1 group by name

insert into rotatetable1(company,box_weight) select name ,'box' from sum1 group by name

update rotatetable1 set 废塑料=box from sum1as a where a.name=rotatetable1.company and box_weight='box' and hsname='废塑料'

update rotatetable1 set 废塑料=weight from sum1as a where a.name=rotatetable1.company and box_weight='weight' and hsname='废塑料'

::: :::

update rotatetable1 set 其它=box from sum1as a where a.name=rotatetable1.company and box_weight='box' and hsname='其它'

update rotatetable1 set 其它=weight from sum1as a where a.name=rotatetable1.company and box_weight='weight' and hsname='其它'

::: :::

update rotatetable1 set 合计=废塑料+废五金+废钢铁+废纸+废有色+废纤维+其它

(所有涉及表的行列转换均可按照这种方式实现。)


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/sjk/9923831.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-03
下一篇 2023-05-03

发表评论

登录后才能评论

评论列表(0条)

保存