子查询中的MySQL COUNT行

时间:2013-11-27 16:13:10

标签: mysql join count subquery

我有这个MySQL声明,它返回了我们所有经销商的清单,以及他们拥有的商店总数。我正在尝试这样做,以便我可以根据商店的joineddate列添加返回的其他列。

这是返回经销商列表(accountgroup)和分配给accountgroup的商店总数/ COUNT的基本声明。

SELECT accountgroup, COUNT(storename) AS TotalAmountOfStores 
FROM accounts 
WHERE accountgroup <>'' 
AND othercode ='Site' 
GROUP BY accountgroup 

我认为在SELECT子查询中使用下面的语句会让我拥有我想要的这些额外列。这个语句可以自行运行,但我无法将其作为子查询成功地加入上述语句中。

SELECT COUNT( storename ) AS  '2months'
FROM  `accounts` 
WHERE joineddate > date_sub(now(), interval 2 month)
AND accountgroup <>  ''
AND othercode =  'Site'
GROUP BY accountgroup

这是我认为会起作用的声明,但我收到错误“#1242 - Subquery返回超过1行,这让我感到困惑,因为它应该返回多行”:

SELECT accountgroup, COUNT(storename) AS TotalAmountOfStores, 
(SELECT COUNT(storename)
FROM `accounts`
WHERE joineddate > date_sub(now(), interval 2 month) AND accountgroup <>'' AND othercode='Site'
GROUP BY accountgroup ) AS '2months' 
FROM accounts 
WHERE accountgroup <>'' 
AND othercode ='Site' 
GROUP BY accountgroup 

我开始觉得子查询不是正确的方法,而且正在阅读JOIN的内容。谁能证实这一点,并可能指出我正确的方向?

非常感谢任何帮助。提前致谢。

1 个答案:

答案 0 :(得分:3)

您可以使用if来汇总此条件为真的时间。例如:

SELECT 
accountgroup, 
COUNT(storename) AS TotalAmountOfStores, 
SUM(
    IF(joineddate > date_sub(now(), interval 2 month), 1, 0) 
) AS '2months'
FROM accounts 
WHERE accountgroup <>'' 
AND othercode ='Site' 
GROUP BY accountgroup