简体   繁体   English

子查询中的MySQL COUNT行

[英]MySQL COUNT rows in a subquery

I've got this MySQL statement that returns a list of all of our dealers, along with total amount of stores they have. 我有这个MySQL声明,它返回了我们所有经销商的清单,以及他们拥有的商店总数。 I'm trying to make it so that I can add additional columns that are returned depending on the stores joineddate column. 我正在尝试这样做,以便我可以根据商店的joineddate列添加返回的其他列。

This is the basic statement that returns the list of dealers (accountgroup) and the total / COUNT of stores that are assigned to accountgroup. 这是返回经销商列表(accountgroup)和分配给accountgroup的商店总数/ COUNT的基本语句。

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

I thought using the below statement in a SELECT subquery would let me have these additional columns that I want. 我想在SELECT子查询中使用下面的语句会让我拥有我想要的这些额外列。 This statement works on it's own, but I haven't been able to encorporate it into the above statement as a subquery successfully. 这个语句可以自行运行,但我无法将其作为子查询成功地加入上述语句中。

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

This is the statement that I thought would work, but I get the error "#1242 - Subquery returns more than 1 row, which confuses me as it should be returning more than one row": 这是我认为可以工作的语句,但我收到错误“#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 

I'm starting to feel that a subquery isn't the right approach, and am reading up on JOIN' s. 我开始觉得子查询不是正确的方法,我正在读JOIN的。 Can anybody confirm this, and possibly point me in the right direction? 谁能证实这一点,并可能指出我正确的方向?

Any help is greatly appreciated. 任何帮助是极大的赞赏。 Thanks in advance. 提前致谢。

You can SUM the times this condition is true using an if. 您可以使用if来汇总此条件为真的时间。 Example: 例:

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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM