当特殊列为空且在MySql中不为null时,查询返回的计数

时间:2013-03-09 05:52:54

标签: mysql hibernate

我想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 个答案:

答案 0 :(得分: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 Fiddle Demo

输出:

Student_With_No_Address |   Student_With_Address
---------------------------------------------
        4               |           6

答案 1 :(得分: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

答案 2 :(得分: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

答案 3 :(得分: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