2012-12-14 147 views
1

行中我有一到十二個月的時間。計算所有12個月的GrandTotal

我有三欄:Year,Month和查詢總數。

我想在底部添加一行來計算總計查詢:

SELECT 
YEAR(date) AS [Year], 
MONTH(date) AS [Month], 
COUNT(*) 
from EnquiryMaster 
Group By YEAR(date), MONTH(date) 

回答

2

你或許應該,而顯示在用戶界面層的總數,但如果你真的想從SQL做到這一點服務器,你可以嘗試像

SELECT YEAR(date) AS [Year], 
     MONTH(date) AS [Month], 
     COUNT(*) 
from EnquiryMaster 
Group By YEAR(date), 
      MONTH(date) 
UNION ALL 
SELECT YEAR(date) AS [Year], 
     NULL, 
     COUNT(*) 
from EnquiryMaster 
Group By YEAR(date) 

而且,也許看看Summarizing Data Using ROLLUP

+2

+1做總計UI層 –

-1
 SELECT YEAR(date) AS [Year], 
      MONTH(date) AS [Month], 
      COUNT(*) 
    from EnquiryMaster 
    Group By YEAR(date), MONTH(date) 

在此查詢中,您將獲得特定年份的每個月的12條記錄,因爲您正在執行GROUP BY年和月,如果您只想要一年的一條記錄,則必須從查詢中刪除MONTH(日期)。

查詢會是這樣: -

 SELECT YEAR(date) AS [Year], 
      MONTH(date) AS [Month], 
      COUNT(*) 
    from EnquiryMaster 
    Group By YEAR 
+0

這個查詢將給予2個原因的錯誤:1,無效的列名年2列是無效的選擇列表,因爲它不包含在聚合函數或GROUP BY子句中。 – Raj

+0

對不起,我沒有看到你在SQL Server中運行這個查詢,這個查詢只能在MySQL數據庫中工作 – Sharad

3

嘗試 「WITH ROLLUP」 SQL的設施。

SELECT YEAR(date), 
MONTH(date), 
count(*) as data_nums 
FROM EnquiryMaster 
GROUP BY YEAR(date),MONTH(date) WITH ROLLUP 

希望這將有助於你