-1

将 3 个 SQL 查询组合成一个返回我想要的所有内容的简单查询时,我遇到了一个大问题。有什么方法可以将这些简单的 sql 查询合并为一个吗?

查询1:

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

查询2:

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

查询3:

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

2 回答 2

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仅计算非空值。

于 2012-10-01T16:40:37.727 回答
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

参考(对于 MySQL)

于 2012-10-01T16:38:37.610 回答