2017-02-27 349 views
0

你好家伙我需要在一个sql查询中使用多个where子句,如下所示,但它不能工作,请帮助我。如何在一个SQL查询中使用多个where子句

select (select count(total) as 'studentMarks1' from School where total <60), 
     (select count(total) as 'studentMarks2' from School where total >80) 
from School 
where Id = '8' 
+0

的数据库您使用的? – Bohemian

回答

2

您最好使用CASE语句像

select SUM(case when total < 60 then 1 else 0 end) as 'studentMarks1', 
     sum(case when total > 80 then 1 else 0 end) as 'studentMarks2' 
from School 
where Id = '8' 
+0

thnks @Rahul它的工作原理,我不知道他们为什么使用'SUM',所以如果我需要使用Sum作为运算符'select sum(total)''那么在查询 – user3518835

+0

@ user3518835不会有问题,这是有条件的总和,并且只有当条件满足总和操作时才会发生加1的总和,与执行计数操作相同。如果它必须是总和,那么你可以像'选择总和(情况当情况,然后总其他0结束)' – Rahul

+0

哦!它炒锅。对不起,我不熟悉'case',但它很棒,所以我想选择所有类似于'select * where total> 50,where total = 40'这是如何工作的? – user3518835

1

您CAU通常用合适的CASE语句做到这一点:

SELECT COUNT(CASE WHEN total < 60 then 1 else NULL END) 
    , COUNT(CASE WHEN total > 80 then 1 else NULL END) 
FROM School 
WHERE ID = '8'