透视此联合查询的结果?

时间:2012-08-27 12:42:50

标签: mysql sql sql-server-2008

我对这些表具有只读权限,需要构建一个查询,根据每个部件号的图像记录计数列出部件号记录的数量。基本上,我需要将结果格式化为:

vendor_desc |具有1个图像的部件数量|具有2个图像的部件数量| ...

VendorXYZ | 250 | 307

我创建了这个联合查询,它在一列中列出了结果,但需要按照图像的数量来分隔列。这是我的联合查询:

SELECT vnd.vendor_desc,
       Count(img1.[part#]) part
FROM   [mytable].[dbo].[parts_images] AS img1
       INNER JOIN mytable.dbo.vendors AS vnd
               ON vnd.vendor_id = LEFT(img1.part#, 3)
       INNER JOIN (SELECT img2.part#,
                          Count(img2.image_file)images
                   FROM   [mytable].[dbo].[parts_images] AS img2
                   GROUP  BY img2.part#
                   HAVING ( Count(img2.image_file) = 1 )) AS img2
               ON img1.part# = img2.part#
GROUP  BY vendor_desc

UNION

SELECT vnd.vendor_desc,
       Count(img1.[part#]) part
FROM   [mytable].[dbo].[parts_images] AS img1
       INNER JOIN mytable.dbo.vendors AS vnd
               ON vnd.vendor_id = LEFT(img1.part#, 3)
       INNER JOIN (SELECT img2.part#,
                          Count(img2.image_file)images
                   FROM   [mytable].[dbo].[parts_images] AS img2
                   GROUP  BY img2.part#
                   HAVING ( Count(img2.image_file) = 2 )) AS img2
               ON img1.part# = img2.part#
GROUP  BY vendor_desc
ORDER  BY vendor_desc

提前致谢!

以下是我正在寻找的结果的查询:

SELECT vnd.vendor_desc,
       Count(img2.[part#]) part
       ,COUNT(img3.part#)
FROM   mytable.[dbo].[parts_images] AS img1
       INNER JOIN mytable.dbo.vendors AS vnd
               ON vnd.vendor_id = LEFT(img1.part#, 3)
       left JOIN (SELECT img2.part#,
                          Count(img2.image_file)images
                   FROM   mytable.[dbo].[parts_images] AS img2
                   GROUP  BY img2.part#
                   HAVING ( Count(img2.image_file) = 1 )) AS img2
               ON img1.part# = img2.part#
               left JOIN (SELECT img3.part#,
                          Count(img3.image_file)images
                   FROM   mytable.[dbo].[parts_images] AS img3
                   GROUP  BY img3.part#
                   HAVING ( Count(img3.image_file) = 2 )) AS img3
               ON img1.part# = img3.part#
GROUP  BY vendor_desc
order by vendor_desc

感谢您的帮助,podiluska!

1 个答案:

答案 0 :(得分:1)

所以

SELECT *
FROM (yourunionquery) src
PIVOT
(COUNT(vendor_desc) FOR part IN ([1],[2],[3], ... )) p

如果您需要可变数量的列,则必须使用动态SQL构建此查询以填充结果列