MySQL 使用 Sum 和 Case

2022-01-09 00:00:00 sql sum mysql case

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

I'm trying to create a GridView with ASP.NET connecting to a MySQL database. The data appears like below.

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

根据上面的记录,我希望结果如下所示

Based on the records above, I'd like the result to appear like below

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

我当前的代码如下.它给了我错误(关于 DatabaseName.sum 的东西不存在.检查函数名称解析和解析'部分...)

My current code is below. It's giving me error (something about DatabaseName.sum does not exist. Check the Function Name Parsing and Resolution' section... )

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 在这里最好用吗?

Is Sum Case the best use here?

推荐答案

函数名和括号之间有空格引起的错误

The error is caused by the space between function name and parenthesis

SUM (CASE WHEN ...
   ^^

阅读更多函数名解析和解析

试试

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 演示

Here is SQLFiddle demo

相关文章