我有一个像下面这样的查询结构,我想知道是否有办法将select查询写成一个使用CASE语句或其他方法,以便根据值来将值插入到适当的变量中。 / p>
DECLARE passes INT;
DECLARE fails INT;
..
SELECT count(score)
INTO passes
FROM scores
WHERE score >= 40;
SELECT count(score)
INTO fails
FROM scores
WHERE score < 40;
默多克想出了一个解决这个问题的简洁方法,我只需要对其进行一次更改,将每个值放入各自的变量中
SELECT *
INTO passes, fails
FROM (SELECT SUM(CASE
WHEN score >= 40 THEN 1
ELSE 0
END) AS _passes,
SUM(CASE
WHEN score < 40 THEN 1
ELSE 0
END) AS _fails
FROM scores) AS x;
答案 0 :(得分:9)
你可以通过为每个分数做一个案例并返回1或0来做到这一点。然后将整个事物包装在SUM(不是COUNT)中,为每个与案例匹配的实例添加一个。
SELECT
SUM(CASE WHEN score >= 40 THEN 1 ELSE 0 END) AS passes,
SUM(CASE WHEN score < 40 THEN 1 ELSE 0 END) AS fails
FROM scores
答案 1 :(得分:3)
DECLARE tpasses INT;
DECLARE tfails INT;
SELECT
SUM(CASE WHEN score >= 40 THEN 1 ELSE 0 END) AS passes,
SUM(CASE WHEN score < 40 THEN 1 ELSE 0 END) AS fails
INTO tpasses, tfails
FROM scores