【问题标题】:Unpivot and Pivot does not return dataUnpivot 和 Pivot 不返回数据
【发布时间】:2015-04-29 21:46:49
【问题描述】:

我正在尝试将数据作为列返回。

我已经编写了这个 unpivot 和 pivot 查询:

`select StockItemCode, barcode, barcode2 from (select StockItemCode, col+cast(seq as varchar(20)) col, value   from  (
select 
  (select min(StockItemCode) 
   from RTLBarCode t2
   where t.StockItemCode = t2.StockItemCode) StockItemCode, 
  cast(BarCode as varchar(20)) barcode, 
     row_number() over(partition by StockItemCode order by StockItemCode) seq
from RTLBarCode t) d  unpivot(
value
for col in (barcode)  ) unpiv) src pivot (  max(value)  for col in (barcode, barcode2)) piv;`

但问题是只有“Barcode2”字段返回一个值(条形码字段返回一个空值,而实际上有一个值。

样本数据

我有一个名为 RTLBarCode 的表 它有一个名为 Barcode 的字段和一个名为 StockItemCode 的字段

对于 StockItemCode = 10,我有 2 行,条形码值为 5014721112824 和 0000000019149。

谁能看出我哪里出错了?

非常感谢

【问题讨论】:

  • 一些样本数据会很好。
  • 老实说,因为您只是取消透视一列,您可能不需要这样做。

标签: pivot unpivot


【解决方案1】:

您正在为 unpiv 中的条形码编制索引。 这导致col's-values barcode1barcode2

但是,您将转向 barcode 而不是 barcode1。未找到任何值,聚合返回 null

正确的说法是:

select StockItemCode, barcode1, barcode2 from 
(
    select StockItemCode, col+cast(seq as varchar(20)) col, value   
    from  
    (
        select 
                (select min(StockItemCode)from RTLBarCode t2 where t.StockItemCode = t2.StockItemCode) StockItemCode,  
                cast(BarCode as varchar(20)) barcode, 
                row_number() over(partition by StockItemCode order by StockItemCode) seq
        from RTLBarCode t
     ) d  
     unpivot(value for col in (barcode)) unpiv
) src 
pivot (max(value) for col in (barcode1, barcode2)) piv

【讨论】:

    猜你喜欢
    • 2016-02-21
    • 1970-01-01
    • 1970-01-01
    • 2019-09-25
    • 1970-01-01
    • 2021-06-13
    • 2022-01-11
    • 2015-11-18
    • 1970-01-01
    相关资源
    最近更新 更多