我对这些表具有只读访问权限,并且需要构建一个查询,该查询将根据每个零件编号的图像记录数列出零件编号记录的计数。本质上,我需要将结果格式化为:
vendor_desc|带有 1 张图像的部件计数|带有 2 张图像的部件计数|...
供应商XYZ|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
感谢您的帮助,波迪卢斯卡!