MySQL统计子查询中的行数
我有一个MySQL语句,它返回我们所有经销商的列表,以及他们拥有的商店总数。我正在尝试这样做,以便可以添加根据stores joineddate列返回的其他列 这是返回经销商accountgroup列表和分配给accountgroup的门店总数/计数的基本语句MySQL统计子查询中的行数,mysql,join,count,subquery,Mysql,Join,Count,Subquery,我有一个MySQL语句,它返回我们所有经销商的列表,以及他们拥有的商店总数。我正在尝试这样做,以便可以添加根据stores joineddate列返回的其他列 这是返回经销商accountgroup列表和分配给accountgroup的门店总数/计数的基本语句 SELECT accountgroup, COUNT(storename) AS TotalAmountOfStores FROM accounts WHERE accountgroup <>'' AND otherco
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-子查询返回多行,这让我感到困惑,因为它应该返回多行:
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的文章。有谁能证实这一点,并为我指出正确的方向吗
非常感谢您的帮助。提前谢谢 您可以使用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
您的预期输出是什么?是的,我可以确认您应该阅读连接