如何在SQL(STUCK)中合并多个WHERE

时间:2018-08-05 07:38:25

标签: mysql sql where where-clause

我如何将这2个数据合并在一起以获得类似的数据 this

SELECT A.schlvl AS School, COUNT(DISTINCT A.name) AS NoOfChild ,SUM(B.cat_id=1) AS Picture 
FROM child AS A INNER JOIN
question AS B 
ON A.child_id=B.child_id
WHERE B.answer=0 AND B.cat_id=1
GROUP BY A.schlvl


SELECT COUNT(DISTINCT A.name) AS Gotitright ,SUM(B.cat_id=2) AS Letters
FROM child AS A INNER JOIN
question AS B 
ON A.child_id=B.child_id
WHERE B.answer = 0 AND B.cat_id = 2
GROUP BY A.schlvl

OR

类似这样的东西,但我对此深信不疑

SELECT A.schlvl AS School, COUNT(DISTINCT A.name WHERE B.answer=0 AND B.cat_id=1) AS Picture , COUNT(DISTINCT A.name WHERE B.answer=0 AND B.cat_id=2) AS Letters
FROM child AS A INNER JOIN
question AS B 
ON A.child_id=B.child_id
GROUP BY A.schlvl

1 个答案:

答案 0 :(得分:0)

根据您的查询。

您可以尝试使用IN中的B.cat_id来获取cat_id子句中的1 2WHERE

使用汇总函数条件CASE WHEN中的SUM

SELECT A.schlvl AS School, COUNT(DISTINCT CASE WHEN B.cat_id = 1 THEN A.name END) AS NoOfChild ,SUM(CASE WHEN B.cat_id IN (1,2) THEN 1 END) AS Picture 
FROM 
child AS A INNER JOIN question AS B ON A.child_id=B.child_id
WHERE B.answer=0 AND B.cat_id= in (1,2)
GROUP BY A.schlvl