我的表格类似于以下内容:
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类型的答案都会有所帮助。
答案 0 :(得分: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
答案 1 :(得分: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
检查语法,但这是基本的想法。真的没有必要加入。
答案 2 :(得分: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类型的答案都会有所帮助。
这是使用SQL Server支持的PIVOT的解决方案:
SELECT
Product,
[2006] AS [2006 Value],
[2007] AS [2007 Value]
FROM Table1
PIVOT(MAX(Value) FOR Year IN ([2006], [2007]))
AS p;