2010-06-14 38 views
3

通過一年數據的比較,我有類似如下表:並排方在SQL

Year | Product | Value 
2006 A   10 
2006 B   20 
2006 C   30 
2007 A   40 
2007 B   50 
2007 C   60 

我想一個查詢將返回以下比較

Product | 2006 Value | 2007 Value 
A   10   40 
B   20   50 
C   30   60 

是什麼這樣做的選擇?它可以在沒有連接的情況下完成嗎?

我正在使用DB2,但所有SQL類型的答案都會有所幫助。

+2

關於在其他DBMS你的問題的一般部分有一個'PIVOT'關鍵詞 – 2010-06-14 20:40:05

回答

8
select Product, 
    max(case when Year = 2006 then Value end) as [2006 Value], 
    max(case when Year = 2007 then Value end) as [2007 Value] 
from MyTable 
group by Product 
order by Product 
3

一個簡單的交叉表查詢應該這樣做

SELECT DISTINCT (year), PRODUCT, 
sum (case when year = 2006 then VALUE else 0 end) as [2006 Value] 
sum (case when year = 2007 then value else 0 end) as [2007 value] 
from table 
group by year, product 

檢查語法,但是這是基本的想法。真的沒有必要加入。

3

你已經有了一些答案不使用加入,但只是比較下面是不使用替代聯接:

SELECT 
    T1.Product, 
    T1.Value AS [2006 Value], 
    T2.Value AS [2007 Value] 
FROM Table1 T1 
JOIN Table1 T2 
ON T1.Product = T2.Product 
AND T1.Year = 2006 
AND T2.Year = 2007 

我使用DB2 ,但所有SQL類型的答案都會有所幫助。

下面是使用PIVOT是SQL Server支持的解決方案:

SELECT 
    Product, 
    [2006] AS [2006 Value], 
    [2007] AS [2007 Value] 
FROM Table1 
PIVOT(MAX(Value) FOR Year IN ([2006], [2007])) 
AS p;