问题
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
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.
回答1:
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
回答2:
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.
回答3:
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;
来源:https://stackoverflow.com/questions/3040680/side-by-side-comparison-of-data-by-year-in-sql