2013-01-16 17 views
1

我有兩個分銷商和訂單表。我想獲得每個月的訂單計數(包括0個計數)我按照客戶月份和年份進行分組。 注:客戶端使用SQL 2000 :(如果在月份和年份中不存在行,則SQL顯示0在子表中計數

這是我想要的

DistID Month Year Orders 
------------------------------ 
1  1  2012  4 
1  2  2012  13 
1  3  2012  5 
2  1  2012  3 
2  2  2012  0 
2  3  2012  0 
3  1  2012  8 
3  2  2012  0 
3  3  2012  3 
4  1  2012  1 
4  2  2012  0 
4  3  2012  1 
5  1  2012  6 
5  2  2012  6 
5  3  2012  0 

這是我得到

DistID Month Year Orders 
------------------------------ 
1  1  2012  4 
1  2  2012  13 
1  3  2012  5 
2  1  2012  3 
3  1  2012  8 
3  3  2012  3 
4  1  2012  1 
4  3  2012  1 
5  1  2012  6 
5  2  2012  6 

我知道爲什麼,就是因爲心不是在一排。訂單表的某些月份。有沒有辦法將計數爲0,如果沒有任何行在訂單表中的那個月和年?

這是我到目前爲止

SELECT 
D.DistID, 
DATEPART(MONTH, Order_Date) AS [Month], 
DATEPART(YEAR, Order_Date) AS [Year], 
SUM(Total_PV) AS TotalPV, 
COUNT(D.DistId) AS Orders 

FROM Distributor D 
LEFT OUTER JOIN Order O ON D.DistID = O.Distributor_ID           
WHERE DATEPART(YEAR, Order_Date) > 2005 
GROUP BY DistID, DATEPART(MONTH, Order_Date), DATEPART(YEAR, Order_Date) 

感謝任何輸入

回答

1

你可以創建一個包含所有幾個月甚至幾年,像表:

create table MonthList(year int, month int); 

如果所有可用年填滿它,然後你可以left join

select o.distributor_id 
,  ml.month 
,  ml.year 
,  sum(o.total_pv) as totalpv 
,  count(d.distid) as orders 
from monthlist ml 
left join 
     [order] o 
on  datepart(year, o.order_date) = ml.year 
     and datepart(month, o.order_date) = ml.month 
where ml.year > 2005 
group by 
     o.distributor_id 
,  ml.month 
,  ml.year 

如果你有沒有需要加入Distributor不要使用該表中的列。

+0

感謝您的回覆。是的,我需要分銷商,因爲我需要考慮表中的每個分銷商。因此0階。 :)任何進一步的想法?這正在擾亂我。 – CodeInColor

+0

我認爲這對於一個SQL人來說是相當直接的。可能會更適合SQL論壇?謝謝! – CodeInColor

相關問題