sql - 如何在不聚合的情况下旋转多个列
问题描述
我使用 SqlServer,我不得不承认我对它不太好......对于高级用户来说,这可能是一个简单的问题(我希望)
我有两张看起来像这样的桌子
第一个表(ID 不是主键)
ID IdCust Ref
1 300 123
1 300 124
2 302 345
第二个(ID 不是主键)
ID Ref Code Price
1 123 A 10
1 123 Y 15
2 124 A 14
3 345 C 18
在第二个表中,列“Ref”是第一个表中“Ref”的外键
我正在尝试产生以下输出:
[编辑]“库存”、“代码”和“价格”列可以有x值,所以我不知道,提前......
我尝试了很多像“PIVOT”这样的东西,但它没有给我正确的结果,所以我希望有人能解决我的问题......
解决方案
使用row_number()
函数并进行条件聚合:
select id, IdCust, Ref,
max(case when Seq = 1 then stock end) as [Stock A], -- second table *id*
max(case when Seq = 1 then code end) as [Code 1],
max(case when Seq = 1 then price end) as [Price1],
max(case when Seq = 2 then stock end) as [Stock B], -- second table *id*
max(case when Seq = 2 then code end) as [Code 2],
max(case when Seq = 2 then price end) as [Price2]
from (select f.*, s.Id Stock, s.Code, s.Price,
row_number() over (partition by f.Ref order by s.id) as Seq
from first f
inner join second s on s.Ref = f.Ref
) t
group by id, IdCust, Ref;
但是,这将与已知值一起使用,否则您需要为此使用动态解决方案。
推荐阅读
- maven - 如何使用 maven 构建 wso2 汽车应用程序?
- json - SSMS:OPENJSON 有效,但不适用于直接 REST 调用
- apache-spark - Spark中Alluxio(Tachyon)和Tungsten的区别?
- vba - 设置 myRange 不设置任何内容
- c++ - Intellisense 不适用于 Visual Studio 2017 中的 cmake 项目
- c# - 返回数组中方法值最高的对象
- shell - 如何合并两个文本文件并创建另一个文本文件并通过 shell 脚本加载到 HIVE 中?
- redis - 使用sadd操作添加后如何检索Redis集合的所有键
- r - 如何在R中打印没有初始行号的文本?
- c# - 在 C# 的管道中调用 powershell cmdlet