我需要帮助显示一个零的字段

时间:2013-03-18 17:39:15

标签: sql list date

在这个查询中,我正在计算上周创建的工单并通过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, -@TodayDayOfWeek, 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

1 个答案:

答案 0 :(得分: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