4

我有一个如下所示的查询结构,我想知道是否有一种方法可以使用 CASE 语句或通过其他方式将选择查询编写为一个查询,以便根据它们的值将值插入到适当的变量中。

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; 
4

2 回答 2

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
于 2011-03-12T13:28:00.500 回答
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
于 2012-05-31T18:36:32.130 回答