MySQL使用Sum和Case

时间:2013-10-22 23:00:49

标签: mysql sql sum case

我正在尝试使用ASP.NET连接到MySQL数据库来创建GridView。数据如下所示。

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 Case最适合使用吗?

1 个答案:

答案 0 :(得分:18)

错误是由函数名称和括号

之间的空格引起的
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 演示