0

我试图将一些数字和项目组合成基本上两列。我有一个包含 7 个 Item 列和 7 个 qty 列以及一个 date 和 id 字段的表。

在此处输入图像描述

即使项目重复,我如何将它们全部组合成基本上几列?我试图做这样的事情: Item1 QTY DATE 与 Item 1 可能重复的次数与其在列中的次数一样多。

结果只需要一列用于项目,一列用于数量,如果可能的话,其旁边的日期列。

这是我当前的选择语句

SELECT TOP (100) PERCENT 
    Item1, Qty1, Item2, Qty2, Item3, Qty3, Item4, Qty4, Item5, Qty5, 
    Item6, Qty6, Item7, Qty7, Date, ID
FROM         
    dbo.ITEMREPORT1
4

2 回答 2

3

你想取消透视。为什么现在每个答案都必须用勺子喂?

select Item, Quantity from
(
  select * from [dbo].[ITEMREPORT1]
  unpivot (
    Item for ItemOriginalColumn in (Item1, Item2, Item3, Item4, Item5, Item6, Item7)
  ) b
  unpivot (
    Quantity for QuantityOriginalColumn in (Qty1, Qty2, Qty3, Qty4, Qty5, Qty6, Qty7)
  ) c
) as d
where 
RIGHT(ItemOriginalColumn,1) = RIGHT(QuantityOriginalColumn, 1)

对于它的价值,我使用了我的答案中的链接,该链接被否决/删除来达到这个解决方案......享受。

于 2013-08-06T21:23:19.233 回答
3

为了将多列转换为多行,您需要对数据进行反透视。如果您使用的是 SQL Server 2008+,则可以使用 VALUES 实现 CROSS APPLY:

select c.item, c.qty, i.date
from dbo.ITEMREPORT1 i
cross apply
(
    values
    (Item1, Qty1),
    (Item2, Qty2),
    (Item3, Qty3),
    (Item4, Qty4),
    (Item5, Qty5),
    (Item6, Qty6),
    (Item7, Qty7)
) c (Item, Qty);

或者您可以将 CROSS APPLY 与 SELECT/UNION ALL 一起使用:

select c.item, c.qty, i.date
from dbo.ITEMREPORT1 i
cross apply
(
    select Item1, Qty1 union all
    select Item2, Qty2 union all
    select Item3, Qty3 union all
    select Item4, Qty4 union all
    select Item5, Qty5 union all
    select Item6, Qty6 union all
    select Item7, Qty7
) c (Item, Qty);
于 2013-08-06T18:31:31.633 回答