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 に答える