Side-by-side comparison of data by year in SQL

喜欢而已 提交于 2019-12-06 01:53:36
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

A simple cross tab query should do it

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

Check the syntax, but that's the basic idea. There is really no need to join.

You've already got some answers that don't use a join, but just for comparison here's an alternative that does use a join:

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

I'm working with DB2, but answers in all SQL types would be helpful.

Here's a solution using PIVOT that SQL Server supports:

SELECT
    Product,
    [2006] AS [2006 Value],
    [2007] AS [2007 Value]
FROM Table1
PIVOT(MAX(Value) FOR Year IN ([2006], [2007]))
AS p;
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!