mySQL中的CASE语句,比较运算符

时间:2017-04-12 03:48:19

标签: mysql case

我不明白为什么这个查询不起作用。它命中一个包含大约15,000条记录的文件。

SELECT emp_id, check_date, case when check_amount <= 300 then check_amount 
end as below_300   FROM `payments` 

它应该仅返回小于300的那些检查,但它返回整个文件全部--15,000条记录。它返回正确的emp_id,check_date但检查金额为“null”。

我正在使用CASE声明,因为我想为低于特定金额($ 300,$ 1,000,$ 2,000等)的支票运行几个阈值。

谢谢!

1 个答案:

答案 0 :(得分:1)

以下是两个可能的答案:

如果您想为每个范围运行单独的查询:

SELECT 
    emp_id, 
    check_date, 
    check_amount
FROM `payments`
WHERE check_amount <= 300

如果您需要有关您提及的群组的摘要信息。

SELECT 
    `emp_id`,
    `check_date`,
    sum(if(`check_amount` <= 300, 1, 0)) as `num_under_300`,
    sum(if(`check_amount` <= 300, `check_amount`, 0)) as `sum_under_300`,
    sum(if(`check_amount` > 300 AND `check_amount` <= 1000, 1, 0)) as `num_under_1000`,
    sum(if(`check_amount` > 300 AND `check_amount` <= 1000, `check_amount`, 0)) as `sum_under_1000`,
    sum(if(`check_amount` > 1000 AND `check_amount` <= 2000, 1, 0)) as `num_under_2000`,
    sum(if(`check_amount` > 1000 AND `check_amount` <= 2000, `check_amount`, 0)) as `sum_under_2000`,
    sum(if(`check_amount` > 2000, 1, 0)) as `num_over_2000`,
    sum(if(`check_amount` > 2000, `check_amount`, 0)) as `sum_over_2000`
FROM `payments`
GROUP BY `emp_id`,`check_date`