I have a litte problem here. I want to join twice from the same table, and group by a common value.
Here is the dataset (from table Voucher):
Date (dd/mm/yyyy) Amount
--------------------------
01.01.2010 1.000
15.01.2010 2.000
01.03.2010 3.000
01.03.2010 4.000
01.05.2010 5.000
01.01.2011 1.000
01.02.2011 2.000
01.04.2011 3.000
15.04.2011 4.000
01.05.2011 5.000
The result should be like this:
Month Amount 2010 Amount 2011
---------------------------------
1 3.000 1.000
2 2.000
3 7.000
4 7.000
5 5.000 5.000
How do I solve this?
Something along these lines will work for this case:
SELECT
DATEPART(month,[Date]) as Month,
SUM(CASE WHEN DATEPART(year,[Date]) = 2010 THEN Amount END) as [Amount 2010],
SUM(CASE WHEN DATEPART(year,[Date]) = 2011 THEN Amount END) as [Amount 2011]
FROM
Voucher
GROUP BY
DATEPART(month,[Date]) as Month
For other situations, you might want to look into PIVOT
.
Date
is a really poor name for a column.
You have to give the tables different names like in this example:
SELECT Fruit1, F1FruitName = F1.FruitName, F1FruitCost = F1.FruitCost,
Fruit2, F2FruitName = F2.FruitName, F2FruitCost = F2.FruitCost FROM T1
JOIN T2 F1 ON Fruit1 = F1.Fruit_ID
JOIN T2 F2 ON Fruit2 = F2.Fruit_ID
The concrete syntax depends on your database system.