一个SQL查询中的不同结果的多个WHERE条件

时间:2012-10-01 16:37:05

标签: sql count

将3个SQL查询合并到一个简单的查询中,我遇到了一个很大的问题。有没有办法将这些简单的SQL查询加入一个?

QUERY1:

SELECT COUNT(FieldID) AS "CountA"
FROM table WHERE Rezervovany = 0 AND Prodany = 0

QUERY2:

SELECT COUNT(FieldID) AS "CountB"
FROM table WHERE Rezervovany = 1 AND Prodany = 0

QUERY3:

SELECT COUNT(FieldID) AS "CountC"
FROM table WHERE Prodany = 1

2 个答案:

答案 0 :(得分:3)

您可以将条件放在汇总case函数内的count子句中:

SELECT Count(CASE 
               WHEN rezervovany = 0 AND prodany = 0 THEN fieldid 
               ELSE NULL 
             END) AS "CountA", 
       Count(CASE 
               WHEN rezervovany = 1 AND prodany = 0 THEN fieldid 
               ELSE NULL 
             END) AS "CountB", 
       Count(CASE 
               WHEN prodany = 1 THEN fieldid 
               ELSE NULL 
             END) AS "CountC" 
FROM   table 

请注意,count仅计算非空值。

答案 1 :(得分:0)

如果你想一个接一个地获取行,你可以这样做:

SELECT COUNT(FieldID) AS "CountA" FROM table WHERE Rezervovany = 0 AND Prodany = 0
union
SELECT COUNT(FieldID) AS "CountB" FROM table WHERE Rezervovany = 1 AND Prodany = 0
union
SELECT COUNT(FieldID) AS "CountC" FROM table WHERE Prodany = 1

Reference (for MySQL)