【问题标题】:MySQL COUNT rows in a subquery子查询中的 MySQL COUNT 行
【发布时间】:2013-11-27 16:13:09
【问题描述】:

我有这个 MySQL 语句,它返回我们所有经销商的列表,以及他们拥有的商店总数。我正在尝试这样做,以便我可以添加根据商店加入日期列返回的其他列。

这是返回经销商列表(帐户组)和分配给帐户组的商店总数/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 - 子查询返回多于 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's。任何人都可以证实这一点,并可能指出我正确的方向吗?

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

【问题讨论】:

  • 您的预期输出是什么?
  • 是的,我可以确认您应该阅读连接

标签: mysql join count subquery


【解决方案1】:

您可以使用 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 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多