0

これらのテーブルへの読み取り専用アクセス権があり、部品番号ごとの画像レコードの数に基づいて部品番号レコードの数をリストするクエリを作成する必要があります。基本的に、結果を次のようにフォーマットする必要があります。

vendor_desc|画像が 1 つのパーツの数|画像が 2 つのパーツの数|...

ベンダーXYZ|250|307

結果を 1 つの列にリストするこのユニオン クエリを作成しましたが、列を画像の数で区切る必要があります。これが私のユニオンクエリです:

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

ポディラスカ、助けてくれてありがとう!

4

1 に答える 1

1

そう

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

可変数の列が必要な場合は、動的 SQL を使用してこのクエリを作成し、結果の列を設定する必要があります。

于 2012-08-27T12:45:41.107 に答える