SQL PIVOT对可变数量的行

时间:2015-10-14 09:52:47

标签: sql-server tsql pivot

我在MSSQL服务器上有以下数据:

Item No_    Unit Of Measure     Qty Per Base UoM    Rounding Precision
000001      PIECE               1                   1.0
000001      PALLET              100                 1.0
000001      BOX                 12                  1.0
000002      KG                  1                   1.0
000002      TON                 1000                0.001

我想获得以下输出:

Item No_    UoM1    Qty pb UoM1 RP1     UoM2    Qty pb UoM2     RP2     UoM3    Qty pb UoM3 RP3
000001      PIECE   1           1.0     PALLET  100             1.0     BOX     12          1.0
000002      KG      1           1.0     TON     1000            0.0001  NULL    NULL        NULL

我尝试使用PIVOT运算符来实现这一点,但它似乎不正确。

实现所需输出的正确方法是什么?

1 个答案:

答案 0 :(得分:4)

对于trully通用解决方案,您需要使用Dynamic-SQL。 但是你说你想要起点,所以我给你一个。您可以使用:

<强> LiveDemo

WITH cte AS
(
   SELECT *, ROW_NUMBER() OVER(PARTITION BY Item_No_ ORDER BY (SELECT 1)) AS rn
   FROM #mytable
)
select Item_No_,
  max(case when rn = 1 then Unit_Of_Measure end) UoM1,
  max(case when rn = 1 then Qty_Per_Base_UoM end) [Qty pb UoM1],
  max(case when rn = 1 then Rounding_Precision end) RP1,
  max(case when rn = 2 then Unit_Of_Measure end) UoM2,
  max(case when rn = 2 then Qty_Per_Base_UoM end) [Qty pb UoM2],
  max(case when rn = 2 then Rounding_Precision end) RP2,
  max(case when rn = 3 then Unit_Of_Measure end) UoM3,
  max(case when rn = 3 then Qty_Per_Base_UoM end) [Qty pb UoM3],
  max(case when rn = 3 then Rounding_Precision end) RP3,
  max(case when rn = 4 then Unit_Of_Measure end) UoM4,
  max(case when rn = 4 then Qty_Per_Base_UoM end) [Qty pb UoM4],
  max(case when rn = 4 then Rounding_Precision end) RP4
from cte
group by Item_No_;

重点是,如果事先知道您的单位数,您可以从1 .. n创建硬编码列。

有关详细信息,请搜索 Dynamic Pivot多列。这是可以实现的,但首先尝试破解这个解决方案。