根据内部选择计数

时间:2017-11-16 17:16:57

标签: mysql sql

我想根据子选择语句进行计数。

SELECT MONTH(Received), State, COUNT('id'), SUM(price) FROM Leads GROUP BY MONTH(Received), State

该查询有效并生成类似这样的内容

MONTH(Received)     State   COUNT('id')    SUM(price)
4                   CA      25             35
4                   UT      13             8

我想要计算的是有多少行有价格> 0

这是我试过的查询

SELECT MONTH(Received), SUM(price), COUNT(`id`), (SELECT COUNT(*) as count FROM Leads WHERE Price > 0) as NumPaidLeads, State FROM Leads GROUP BY MONTH(Received), State

但是NumPaidLeads计算整个列,价格列是数字类型。

我做错了什么?

2 个答案:

答案 0 :(得分:1)

在您的情况下,计算价格>的行0你可以使用案例

SELECT MONTH(Received), State, 
 sum( case when price > 0 then 1 else 0 END) num_row_with_price, SUM(price) 
FROM Leads 
GROUP BY MONTH(Received), State

答案 1 :(得分:1)

您忘记在子选择的where子句中包含。 但是,另一篇文章中的案例解决方案可能会更快。

SELECT MONTH(Received), SUM(price), COUNT(`id`), 
 (SELECT COUNT(*) as count FROM Leads as L1 WHERE Price > 0 
  and L1.State=L2.State) as NumPaidLeads,
 State FROM Leads as L2 GROUP BY MONTH(Received), State