gpt4 book ai didi

MySQL 使用 Sum 和 Case

转载 作者:IT老高 更新时间:2023-10-29 00:07:13 26 4
gpt4 key购买 nike

我正在尝试使用连接到 MySQL 数据库的 ASP.NET 创建一个 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 是最好的用法吗?

最佳答案

该错误是由函数名和括号之间的空格引起的

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

关于MySQL 使用 Sum 和 Case,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19529864/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com