user955289
user955289

Reputation: 171

Pivot the results from this union query?

I have read-only access to these tables, and need to build a query that will list the count of part number records based on the count of image records per part number. Essentially, I need the results to be formatted like this:

vendor_desc|Count of parts with 1 image|Count of parts with 2 images|...

VendorXYZ|250|307

I made this union query that lists the results in one column, but need the columns to be separated by count of images. Here is my union query:

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

Thanks in advance!

Here is the query for the result that I was looking for:

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

Thanks for your help, podiluska!

Upvotes: 0

Views: 436

Answers (1)

podiluska
podiluska

Reputation: 51494

So

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

If you need a variable number of columns, you'll have to construct this query using dynamic SQL to populate the result columns

Upvotes: 1

Related Questions