1

次のようなテーブルがあります。

ManufacturerID   ProductID     Price    Region
==============================================
100              1             12.00    A
100              2             20.00    A
100              3             25.00    A
100              4             30.00    B
101              1             15.00    A
101              2             20.00    A
101              4             30.00    B

2 つの異なるメーカーを比較して、次のようなクエリ結果を取得したいと考えています。

ProductID     Price1    Price2    Region
=========================================================================
1             12.00     15.00     A
2             20.00     20.00     A
3             25.00     null      A
4             30.00     30.00     B

同じテーブルで左結合を使用しようとしています:

SELECT ProductID, a.Price AS Price1, b.Price AS Price2, a.Region
FROM   table1 a 
       LEFT JOIN table1 b ON a.ProductID = b.ProductID AND a.ManufacturerID = 100
WHERE  b.ManufacturerID = 101

しかし、これは製造元 101 の不足している製品 (ID:4) を提供しません。何が不足していますか?

4

3 に答える 3

2

結合ではなく、集計を使用してこれを行います。

select ProductId,
       MAX(case when ManufacturerId = 100 then Price end) as Price1,
       MAX(case when ManufacturerId = 101 then Price end) as Price2,
       Region
from table1
where ManufacturerId in (100, 101)
group by ProductId, Region;
于 2013-05-16T18:45:08.253 に答える
1

どの製品が欠落するかを事前に知ることはできないため、たとえばメーカー A には製品 3 が欠落しており、製造 B には製品 8 が欠落している可能性があるFULL OUTERため、これを結合で行いたい場合は結合が必要です (Gordon は別の方法を提供しました)。トーゴ)。

(ManufacturerID ,ProductID, Region)組み合わせにはUNIQUE制約があると想定しました。

SELECT COALESCE(a.ProductID, b.ProductID) AS ProductID, 
       a.Price AS Price1, 
       b.Price AS Price2, 
       COALESCE(a.Region, b.Region) AS Region
FROM   
       ( SELECT ProductID, Price, Region
         FROM table1
         WHERE ManufacturerID = 100
       ) AS a
    FULL JOIN 
       ( SELECT ProductID, Price, Region
         FROM table1
         WHERE ManufacturerID = 101
       ) AS b
           ON  a.ProductID = b.ProductID 
           AND a.Region = b.Region      -- not sure if you need this line
;

SQL-Fiddle (thnx @Thomas)でテスト済み

于 2013-05-16T18:54:38.373 に答える