如何解决SQL 将行转换为列并展平
我一直在 PIVOT、UNPIVOT 和其他中寻找解决方案,但仍然没有看到我的方案。我有一个表中的项目。为简单起见,我们只说 PartNum、Desc。这些东西可以定制。颜色、高度、宽度、深度等属性存储在单独的表格中,并用代码指示哪个属性。
OrderId - PartNum - Desc (join from inv)
1 12345 - Block A
2 12345 - Block A
3 23456 - Block B
4 23456 - Block B
两个客户得到 12345,两个得到 23456,他们有宽度、高度和深度...
AttrId - OrderId - CCode - Value
1 1 WIDTH 10
2 1 HEIGHT 10
3 1 DEPTH 1
4 2 WIDTH 20
5 2 HEIGHT 10
6 2 DEPTH 1
7 3 WIDTH 10
8 3 HEIGHT 20
9 3 DEPTH 2
10 4 WIDTH 10
11 4 HEIGHT 20
12 4 DEPTH 2
我不能在值上使用带有聚合的枢轴,因为我需要像这样对每个部分、宽度、高度和深度的组合进行分组
PartNum - Width - Height - Depth - Count - Area (w x h x count)
12345 10 10 1 1 100
12345 20 10 1 1 200
23456 10 20 2 2 400
我尝试使用 CCode 进行 case 语句,但在某些行中得到空值,因此分组不起作用。如果这有所不同,这在 sql Server 2019 中。有人可以帮忙解决这个问题吗?
解决方法
这是你想要的吗?
select t1.partnum,t2.width,t2.height,t2.depth,count(*) as cnt
from t1 join
(select t2.orderid,sum(case when ccode = 'width' then value end) as width,sum(case when ccode = 'height' then value end) as height,sum(case when ccode = 'depth' then value end) as depth
from t2
group by t2.orderid
) t2
on t2.orderid = t1.orderid
group by t1.partnum,t2.depth;
我推测您可能想要:
sum(t2.width * t2.height * t2.depth) as area
但数字与您问题中的值不一致。
Here 是一个 dbfiddle。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。