首页 > 解决方案 > 如何在不聚合的情况下旋转多个列

问题描述

我使用 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”这样的东西,但它没有给我正确的结果,所以我希望有人能解决我的问题......

标签: sqlsql-serversql-server-2008sql-server-2012

解决方案


使用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;

但是,将与已知值一起使用,否则您需要为此使用动态解决方案。


推荐阅读