2015-05-22 51 views
0

我寫了一個查詢像如何在SQL Server 2008中顯示一個月的所有日子?

SELECT 
    Sum(a.in_total) as Totall, 
    DATEPART(dd, a.in_date_issued) as dateissued 
FROM   
    dbo.IN_Invoices as a 
WHERE 
    DATEPART(mm, a.in_date_issued) = 5 
AND DATEPART(yyyy, a.in_date_issued)= 2015 
AND a.sy_id='DPI' 
AND EXISTS(SELECT DISTINCT cl_id as clid 
      FROM dbo.cloi_clientorderitems as c 
      WHERE c.masterorderid=a.masterorderid) 
--AND c.cl_id NOT IN ('100001_DPO')) 
GROUP BY 
    DATEPART(dd, a.in_date_issued) 
ORDER BY dateissued ASC 

這個查詢將寫入了讓像

Total| day 
100 | 1 
0 | 3 
150 | 10 
- 
- 
200 | 31 

預計輸出

Total| day 
100 | 1 
150 | 2 
0 | 3 
600 | 4 
- 
- 
200 | 31 

請幫我在該查詢。

+0

當你使用'GROUP BY DATEPART(DD,a.in_date_issued)'你一定會還'ORDER BY DATEPART(DD,a.in_date_issued)asc'?嘗試一下,讓我知道。 –

+0

沒有相同的結果..沒有得到預期的結果,因爲我顯示 –

+0

啊,好吧。這是在黑暗中拍攝的。我對sql-server做的這麼少,以至於超出了我的經驗範圍。 –

回答

1

你可以嘗試這樣的事情:

DECLARE @y INT; 
DECLARE @m INT; 

SET @y = 2015; 
SET @m = 5; 

WITH 
m AS(SELECT 1 AS d UNION ALL SELECT d+1 FROM m WHERE d < datediff(d, DATEADD(mm, @m - 1, CAST(@y AS VARCHAR(8)) + '0101'), dateadd(m, 1, DATEADD(mm, @m - 1, CAST(@y AS VARCHAR(8)) + '0101')))) 

SELECT isnull(Totall, 0) AS Totall, m.d AS dateissued 
FROM m 
LEFT JOIN(

SELECT SUM(a.in_total) AS Totall , 
     DATEPART(dd, a.in_date_issued) AS dateissued 
FROM dbo.IN_Invoices AS a 
WHERE DATEPART(mm, a.in_date_issued) = @m 
     AND DATEPART(yyyy, a.in_date_issued) = @y 
     AND a.sy_id = 'DPI' 
     AND EXISTS (SELECT DISTINCT 
          cl_id AS clid 
        FROM dbo.cloi_clientorderitems AS c 
        WHERE c.masterorderid = a.masterorderid) 
        --and c.cl_id not in ('100001_DPO')) 
GROUP BY DATEPART(dd, a.in_date_issued) 
)t ON m.d = t.dateissued 
ORDER BY m.d ASC 
+0

得到這個錯誤「消息139,級別15,狀態1,行0 無法將默認值分配給局部變量 消息137,級別15,狀態2,第4行 必須聲明標量變量「@d」 Msg 137,Level 15,State 2,Line 13 必須聲明標量變量「@d」。語法靠近關鍵字'GROUP'。 「 –

+0

SQL Server的版本是什麼? –

+0

過期日期('20150501')我們可以通過年份和月份嗎? –

相關問題