Case Statement jest moim najlepszym przyjacielem sql. Potrzebujesz również tabeli czasu, aby wygenerować 0 obrotów w obu miesiącach.
Założenia oparte są na dostępności następujących tabel:
i
Przykład 1 bez pustych wierszy:
select
Category
,month
,SUM(CASE WHEN YEAR = 2008 THEN Revenue ELSE 0 END) this_year
,SUM(CASE WHEN YEAR = 2007 THEN Revenue ELSE 0 END) last_year
from
sales
where
year in (2008,2007)
group by
Category
,month
ZWROTY:
Category | Month | Rev. This Year | Rev. Last Year
Bikes 1 10 000 0
Bikes 2 12 000 11 000
Bikes 3 12 000 11 500
Bikes 4 0 15 400
Przykład 2 z pustymi wierszami:Zamierzam użyć podzapytania (ale inne mogą nie) i zwrócę pusty wiersz dla każdego produktu i kombinacji rok-miesiąc.
select
fill.Category
,fill.month
,SUM(CASE WHEN YEAR = 2008 THEN Revenue ELSE 0 END) this_year
,SUM(CASE WHEN YEAR = 2007 THEN Revenue ELSE 0 END) last_year
from
sales
Right join (select distinct --try out left, right and cross joins to test results.
product
,year
,month
from
sales --this ideally would be from a products table
cross join tm
where
year in (2008,2007)) fill
where
fill.year in (2008,2007)
group by
fill.Category
,fill.month
ZWROTY:
Category | Month | Rev. This Year | Rev. Last Year
Bikes 1 10 000 0
Bikes 2 12 000 11 000
Bikes 3 12 000 11 500
Bikes 4 0 15 400
Bikes 5 0 0
Bikes 6 0 0
Bikes 7 0 0
Bikes 8 0 0
Zwróć uwagę, że większość narzędzi do raportowania wykona tę funkcję tabeli krzyżowej lub macierzy, a teraz, gdy o tym myślę, SQL Server 2005 ma składnię pivot, która również to zrobi.
Oto kilka dodatkowych zasobów.CASEhttp://www.4guysfromrolla.com/webtech/ 102704-1.shtml SQL SERVER 2005 PIVOThttp://msdn.microsoft.com/en-us /biblioteka/ms177410.aspx