MySQL - 带有SUM的DISTINCT

时间:2017-09-20 14:10:11

标签: mysql group-by sum distinct having

我有一个包含以下列的表:

  • customerID - 具有相同ID的多行的客户ID
  • actionVal - 0或1

我想计算有多少客户(customerID)有多行(actionVal)等于1

我提出这个SQL语句没有运气......

SELECT customerID, SUM(actionVal), COUNT(DISTINCT customerID) as total_C
FROM table1 
GROUP BY customerID 
HAVING SUM(actionVal) > 1

我正在寻找的结果是['total_C']

2 个答案:

答案 0 :(得分:1)

关闭,您只需要从查询中计算客户数量:

SELECT COUNT(*) as total_C
FROM (
  SELECT customerID, SUM(actionVal)
  FROM table1 
  GROUP BY customerID 
  HAVING SUM(actionVal) > 1
) as q;

答案 1 :(得分:1)

您必须计算查询返回的行数。 这样的事情。

SELECT COUNT(1) FROM (
SELECT customerID, SUM(actionVal) as act_sum
FROM table1 
GROUP BY customerID 
HAVING act_sum > 1
) AS tab

我希望这会有所帮助。