0

以下查询:

SELECT  i.Item_ID

  FROM  AGR_Header ah
        LEFT JOIN AGR_Detail ad
               ON ad.AGR_Header_RecID = ah.AGR_Header_RecID
        LEFT JOIN IV_Item i
               ON i.IV_Item_RecID = ad.IV_Item_RecID

显示以下结果:

a4 black usage page count
a4 colour usage page count
a4 black usage page count
a4 colour usage page count
a4 black usage page count
a4 colour usage page count
a4 black usage page count
a4 colour usage page count

有没有办法为每个 Item_ID 创建一列,使其显示如下:

A4 Black                     A4 Colour
a4 black usage page count    a4 colour usage page count
a4 black usage page count    a4 colour usage page count
a4 black usage page count    a4 colour usage page count
a4 black usage page count    a4 colour usage page count

我已经阅读了有关使用 ROW_NUMBER 为每个 Item_ID 分配序列号或使用 PIVOT ...不熟悉这些或任何其他方式来完成此操作的信息,因此不胜感激。

干杯

4

1 回答 1

3

如果您的输出与您提到的一样,那么您只需为所需的输出执行以下操作:

SELECT 
    ISNULL(a4b.Item_ID, '') 'A4 Black', 
    ISNULL(a4c.Item_ID, '') 'A4 Color'
FROM
(
  SELECT    i.Item_ID, ROW_NUMBER() OVER(ORDER BY i.Item_ID ASC) 'RowNum'

  FROM  AGR_Header ah
        LEFT JOIN AGR_Detail ad
               ON ad.AGR_Header_RecID = ah.AGR_Header_RecID
        LEFT JOIN IV_Item i
               ON i.IV_Item_RecID = ad.IV_Item_RecID
  WHERE i.Item_ID LIKE 'a4 black%'
) AS a4b
FULL OUTER JOIN
(
  SELECT    i.Item_ID, ROW_NUMBER() OVER(ORDER BY i.Item_ID ASC) 'RowNum'

  FROM  AGR_Header ah
        LEFT JOIN AGR_Detail ad
               ON ad.AGR_Header_RecID = ah.AGR_Header_RecID
        LEFT JOIN IV_Item i
               ON i.IV_Item_RecID = ad.IV_Item_RecID
  WHERE i.Item_ID LIKE 'a4 color%'
) AS a4c
ON a4b.RowNum = a4c.RowNum

OUTER JOIN 将处理 a4 black 和 a4 color 的条目数不同的情况。

于 2012-11-12T05:10:10.833 回答