0

我想select a count returned by a query when a particular column is null和另一个query to select a count when that column is not null进入单个查询我怎样才能实现它..?

我尝试了一些在 SOF 中可用但没有用的示例。

例如我想

select students count of class table where the address null and notnull
4

4 回答 4

3

在 MySQL 中,这可以做到

SELECT 
    SUM(IF(address IS NULL,1,0))       as  `Student_With_No_Address`,
    SUM(IF(address IS NOT NULL,1,0)) as    `Student_With_Address`
FROM students

SQL 小提琴演示

输出 :

Student_With_No_Address |   Student_With_Address
---------------------------------------------
        4               |           6
于 2013-03-09T06:15:23.437 回答
2

试试这个

SELECT 
COUNT(CASE when address is null then 1 end) AS StudentsWithNoAddress,
COUNT(CASE when address is not null then 1 end) AS StudentsWithAddress 
FROM Class
于 2013-03-09T06:02:38.030 回答
1

您必须编写两个SELECT语句并将它们组合使用UNION

SELECT 'No Address' AS AddressStatus, COUNT(*) AS NoOfStudents 
FROM Class WHERE Address IS NULL
UNION
SELECT 'With Address' AS AddressStatus, COUNT(*) AS NoOfStudents 
FROM Class WHERE Address IS NOT NULL
于 2013-03-09T05:58:59.403 回答
0
select 
 SUM( CASE when studentId is not NULL THEN 1 else 0 END ) as result1 ,
 SUM( CASE when studentId is NULL THEN 1 else 0 END) as result2
from class
于 2013-03-09T07:02:26.553 回答