【问题标题】:Mysql Select count with conditional statement带有条件语句的Mysql选择计数
【发布时间】:2021-03-17 03:56:58
【问题描述】:

我被指示进行一个查询,如果该值大于零并且另一列等于零且大于零,则对一列进行计数。我尝试将CASE 用于mysql,但它不起作用。谁能告诉我我错过了什么?这是我尝试过的

SELECT 
COUNT(CASE WHEN aci.approved > 0) as approved, 
COUNT(CASE WHEN aci.approved == 0 AND aci.pending > 0) as pending 
from `admin_case_info` as `aci` 
inner join `users_mws` on `users_mws`.`id` = `aci`.`users_mws_id` 
inner join `users` on `users`.`id` = `users_mws`.`user_id` 
where `users`.`status` not in ('Dumped','Dumped2') 
and `aci`.`case_type` = 'INBOUND_SHIPMENT'

我得到的例外是

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ') as approved,
COUNT(CASE WHEN aci.approved == 0 AND aci.pending > 0) as pendi' at line 2

【问题讨论】:

  • 在没有ORDER BY 的情况下使用LIMIT 毫无意义。在整个表中选择COUNT 并使用LIMIT 10 也是没有意义的。请在您的问题中添加示例数据。
  • 哦,对不起。我添加了测试限制。对不起,请忽略限制先生@TimBiegeleisen

标签: mysql database mariadb


【解决方案1】:

您可以对布尔表达式求和,这与您尝试的语法很接近:

SELECT
    SUM(aci.approved > 0) AS approved,
    SUM(aci.approved = 0 AND aci.pending > 0) AS pending
FROM admin_case_info AS aci
INNER JOIN users_mws ON users_mws.id = aci.users_mws_id
INNER JOIN users ON users.id = users_mws.user_id
WHERE users.status NOT IN ('Dumped', 'Dumped2') AND aci.case_type = 'INBOUND_SHIPMENT';

【讨论】:

  • 和伯爵一样吗?因为我试图根据条件计算列数
  • 回答:是的,上面的逻辑会计算布尔表达式为真的次数(真为 1,假为 0)。自己试试代码。
  • 尝试使用它,但它给了我一个You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '= 0 AND aci.pending > 0) AS pending FROM admin_case_info AS aci INNER JOIN use' at line 3
  • SUM(aci.approved = 0 ...) 不要使用==表示相等,只使用=
【解决方案2】:

你忘了结束 case 函数

(案例 当你的条件然后结果1 当你的条件然后结果2 其他结果 结束);

【讨论】:

  • 你能举个例子吗?
【解决方案3】:
SELECT 
customerName, 
orderCount,
CASE orderCount
    WHEN 1 THEN 'One-time Customer'
    WHEN 2 THEN 'Repeated Customer'
    WHEN 3 THEN 'Frequent Customer'
    ELSE 'Loyal Customer'
end customerType

来自 cte 按客户名称订购;

【讨论】:

    猜你喜欢
    • 2017-07-06
    • 2013-02-25
    • 1970-01-01
    • 2013-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-20
    • 1970-01-01
    相关资源
    最近更新 更多