2015-12-02 57 views
-1

我有一個查詢按月搜索錯誤原因和錯誤原因的計數。SQL:什麼是不存在的報告

Select datepart(month,CL.[errorDate]) As Month, 
ErrorReason As 'Errors' 
Count(ErrorReason) 
From ErrorTable 
Group BY datepart(month,errorDate), ErrorReason 

這很好。 如果我有10倍錯誤的原因

Reason 1 
Reason 2 
Reason 3 

... and so on 

並在一個月有理性2.然後它不會返回結果沒有錯誤。

我怎樣才能改變這個查詢,所以它會返回月份數,錯誤原因而錯誤計數爲0

感謝

+0

多少個月,你想顯示? –

+1

什麼是全表結構?你有一個單獨的表,其中包含原因 –

+0

如果一個月沒有任何理由?例如1838年5月。 – jarlh

回答

1

您可以使用日期表這個。有一份加入日期的列表,通過提供每個月的記錄,無論錯誤的數量如何,都能爲您提供所需的所有值。

在這個例子中,我使用遞歸CTE實時創建了一個日期表。但是物理表也可以工作。我還創建了第二個CTE,其中包含一些示例數據,以便任何人都可以運行該示例。

Example

DECLARE @StartMonth DATE = '2015-01-01'; 
DECLARE @EndMonth DATE = '2015-03-01'; 

WITH SampleError AS 
    (
     /* This CTE returns sample error records. 
     * There are two entrie for Jan and Mar. 
     * None for Feb. 
     */ 
     SELECT 
      r.ErrorDate, 
      r.ErrorReason 
     FROM 
      (
       VALUES 
        ('2015-01-01', 1), 
        ('2015-01-02', 1), 
        ('2015-03-01', 1), 
        ('2015-03-02', 2) 
      ) AS r(ErrorDate, ErrorReason) 
    ), 
    DateTable AS 
    (
     /* This CTE creates a date table. 
     * You could replace with with a 
     * real table. 
     * It uses recurision to populate the rows. 
     */ 
      SELECT 
       @StartMonth  AS [Month] 

     UNION ALL 

      SELECT 
       DATEADD(MONTH, 1, [Month])  AS [Month] 
      FROM 
       DateTable 
      WHERE 
       [Month] < @EndMonth 
    ) 
SELECT 
    dt.[Month], 
    SUM(CASE WHEN se.ErrorReason = 1 THEN 1 ELSE 0 END)  AS Error1Count, 
    SUM(CASE WHEN se.ErrorReason = 2 THEN 1 ELSE 0 END)  AS Error2Count 
FROM 
    DateTable AS dt 
     LEFT OUTER JOIN SampleError AS se  ON MONTH(se.ErrorDate) = MONTH(dt.[Month]) 
               AND YEAR(se.ErrorDate) = YEAR(dt.[Month]) 
GROUP BY 
    dt.[Month] 
; 
0
SELECT m.MonthName, r.ErrorReason, 
    (SELECT COUNT(*) 
    FROM ErrorTable e2 
    WHERE datepart(month,e2.errorDate) = m.MonthName AND e2.ErrorReason = r.ErrorReason) 
FROM (
    SELECT datepart(month,errorDate) As MonthName 
    FROM ErrorTable 
    GROUP BY datepart(month,errorDate) 
) m CROSS JOIN 
( 
    Select ErrorReason 
    FROM ErrorTable 
    GROUP BY ErrorReason 
) r