2013-10-22 73 views
7

我想創建一個與ASP.NET連接到MySQL數據庫的GridView。數據如下所示。MySQL使用總結和案例

BusinessUnit OrderDate  Canceled 
UnitA   1/15/2013   N 
UnitA   10/1/2013   N 
UnitB   10/15/2013   N 
UnitB   10/22/2013   N 
UnitB   10/22/2013   N 

基於以上的記錄,我想結果出現類似下面

BusinessUnit TodaysOrders ThisMonthsOrders ThisYearsOrders 
UnitA    0    1    2 
UnitB    2    3    3 

我當前的代碼如下。它給我的錯誤(一些有關DatabaseName.sum不存在。檢查 功能名稱解析和解決方案」部分...)

Select 
    SUM (CASE WHEN (OrderDate)=DATE(NOW()) THEN 1 ELSE 0 END) AS TodaysOrders, 
    SUM (CASE WHEN YEAR(OrderDate) = YEAR(CURDATE()) AND MONTH(OrderDate) = MONTH(CURDATE()) THEN 1 ELSE 0 END) AS ThisMonthsOrders, 
    SUM (CASE WHEN YEAR(main_order_managers.creation_date) = YEAR(CURDATE()) THEN 1 ELSE 0 END) AS ThisYearsOrders 

代碼繼續

FROM OrderTable WHERE OrderTable.Canceled. <> 'Y'; 

是sum情況下,最好使用這裏?

+0

你的背景總和(殼體)按預期好,但根據Peterm的間隔答案可能是您的問題......(但是,取消取消後的期限。在<>'Y'之前) – DRapp

回答

12

錯誤是由函數名和括號之間的空間

SUM (CASE WHEN ... 
    ^^ 

閱讀造成了更多Function Name Parsing and Resolution

嘗試

SELECT BusinessUnit, 
     SUM(CASE WHEN OrderDate = CURDATE() THEN 1 ELSE 0 END) TodaysOrders, 
     SUM(CASE WHEN DATE_FORMAT(OrderDate, '%Y%m') = DATE_FORMAT(CURDATE(), '%Y%m') THEN 1 ELSE 0 END) ThisMonthsOrders, 
     SUM(CASE WHEN YEAR(OrderDate) = YEAR(CURDATE()) THEN 1 ELSE 0 END) ThisYearsOrders 
    FROM OrderTable 
WHERE Canceled <> 'Y' 
GROUP BY BusinessUnit 

這裏是SQLFiddle演示