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, -@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
4

1 回答 1

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
于 2013-03-18T17:48:28.287 回答