2013-03-18 42 views
0

在此查詢中,我計算了上週創建的工作訂單並顯示了wotype2的計數。如果前一週的wotype2爲零,我需要將wotype2顯示在我的結果中。關於如何解決這個問題的任何想法?我需要顯示零的字段的幫助

-- Retrieve Last Week's New Work Orders. 

DECLARE @TodayDayOfWeek INT 
DECLARE @EndOfPrevWeek DateTime 
DECLARE @StartOfPrevWeek DateTime 

--get number of a current day (1-Monday, 2-Tuesday... 7-Sunday) 
SET @TodayDayOfWeek = datepart(dw, GetDate()) 
--get the last day of the previous week (last Sunday) 
SET @EndOfPrevWeek = DATEADD(dd, [email protected], GetDate()) 
--get the first day of the previous week (the Monday before last) 
SET @StartOfPrevWeek = DATEADD(dd, -(@TodayDayOfWeek+6), GetDate()) 


SELECT wotype2 as WOType, COUNT(*) as NewWOsLastWeek 
FROM tasks 
WHERE ((OpenDATE BETWEEN 
    CONVERT(VARCHAR, @StartOfPrevWeek,7) AND 
    CONVERT(VARCHAR, @EndOfPrevWeek+1,7)) AND 
    (TYPE = 'Information Systems')  AND 
    (RESPONS != 'ADMIN')) 
group by wotype2 
order by wotype2 
+0

是* wotype2真的*零或可能是'NULL'? – 2013-03-18 17:41:54

回答

1

您可能需要使用包含wotype2所有可能值的表進行外連接(如左外連接)。

如果有這樣一個表,假設它的命名wotype2s,那麼SQL將是:

SELECT wotype2s.wotype2 as WOType, COUNT(*) as NewWOsLastWeek 
FROM wotype2s left outer join tasks on wotype2s.wotype2 = tasks.wotype2 
WHERE ((OpenDATE BETWEEN 
    CONVERT(VARCHAR, @StartOfPrevWeek,7) AND 
    CONVERT(VARCHAR, @EndOfPrevWeek+1,7)) AND 
    (TYPE = 'Information Systems')  AND 
    (RESPONS != 'ADMIN')) 
group by wotype2s.wotype2 
order by wotype2s.wotype2 

,或者,如果沒有這樣的表,

SELECT wotype2s.wotype2 as WOType, COUNT(*) as NewWOsLastWeek 
FROM (select distinct wotype2 from tasks) wotype2s 
    left outer join tasks on wotype2s.wotype2 = tasks.wotype2 
WHERE ((OpenDATE BETWEEN 
    CONVERT(VARCHAR, @StartOfPrevWeek,7) AND 
    CONVERT(VARCHAR, @EndOfPrevWeek+1,7)) AND 
    (TYPE = 'Information Systems')  AND 
    (RESPONS != 'ADMIN')) 
group by wotype2s.wotype2 
order by wotype2s.wotype2