Comparison of data by year in SQL

I have a 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 need a query that will return the following comparison

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

What are the options for this? Can this be done without connections?

I work with DB2, but answers to all types of SQL will be helpful.

+3
source share
3 answers
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
+8
source

A simple cross-tab query should do this

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 this is the main idea. No need to join.

+3
source

, , , :

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;
+3

Source: https://habr.com/ru/post/1750007/


All Articles