简体   繁体   English

MySQL-具有总和的DISTINCT

[英]MySQL - DISTINCT with HAVING SUM

I have a table with the following columns: 我有一个包含以下列的表格:

  • customerID - customer IDs with multiple rows with same ID customerID具有相同ID的多行客户ID
  • actionVal - 0 or 1 actionVal -0或1

I want to count how many customers ( customerID ) have more then one row with ( actionVal ) equal to 1 我想计算有多少个客户( customerID )的一行actionValactionVal )等于1

I came up with this SQL statement with no luck... 我想出了这个SQL语句,没有运气...

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

The result I'm looking for would be ['total_C'] 我要寻找的结果将是['total_C']

Close, you just need to count the customers from your query: 关闭,您只需要从查询中计算出客户:

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

You will have to count the rows returned by your query . 您将必须计算查询返回的行。 Something like this. 这样的事情。

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

I hope this helped. 希望对您有所帮助。

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

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