开发者

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

开发者 https://www.devze.com 2023-01-03 05:36 出处:网络
I have table similar to the following: Year | Product |Value 2006A10 2006B20 2006C30 2007A40 2007B50 2007C60

I have table similar to the following:

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

I would like a query that would return the following comparison

开发者_StackOverflow社区
Product | 2006 Value | 2007 Value
A         10           40
B         20           50
C         30           60

What are the options to do so? Can it be done without joins?

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


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;
0

精彩评论

暂无评论...
验证码 换一张
取 消