我可以在同一个查询中计算两个不同的东西吗?

时间:2017-05-20 16:01:08

标签: mysql sql count

我有一张这样的表:

// question_and_answers
+----+---------+---------------+--------+------+
| id |  title  |      body     | amount | type |
+----+---------+---------------+--------+------+
| 1  | t1      | b1            | NULL   | 0    |
| 2  | t2      | b2            | NULL   | 1    |
| 3  | t3      | b3            | NULL   | 1    |
| 4  | t4      | b4            | 100    | 0    |
| 5  | t5      | b5            | NULL   | 0    |
| 6  | t6      | b6            | NULL   | 1    |
| 7  | t7      | b7            | 50     | 0    |
+----+---------+---------------+--------+------+

我有两个问题:

1:问题数量:

SELECT count(1) FROM question_and_answers WHERE type = 0

2:付费问题的数量:

SELECT count(1) FROM question_and_answers WHERE type = 0 AND amount IS NOT NULL

我可以将这两个查询结合起来吗?我的意思是我可以写一个查询而不是它们吗?

2 个答案:

答案 0 :(得分:3)

您可以使用条件聚合:

SELECT sum(type = 0 AND amount IS NOT NULL),
       count(*) 
FROM question_and_answers 
WHERE type = 0

在MySQL中,比较结果为01。您可以像上面的查询一样对这些结果进行求和。

要使其适用于其他数据库引擎,您可以使用这种通用的ANSI SQL方法:

SELECT sum(case when type = 0 AND amount IS NOT NULL then 1 else 0 end),
       count(*)
FROM question_and_answers 
WHERE type = 0

count()

SELECT count(case when type = 0 AND amount IS NOT NULL then 1 else null end),
       count(*) 
FROM question_and_answers 
WHERE type = 0

答案 1 :(得分:1)

您可以使用点击查询:

select count(1) as count1  , sum(if(amount is not null,1,0)) as count2 from question_and_answers where type=0
对于(type = 0)的计数,

count1 , 计数为 count2 (type = 0且amount不为null)。 如果使用sql server,请在查询中使用IIF而不是IF。