具有特定条目数

时间:2017-03-21 23:42:47

标签: mysql sql group-by

您好我正在尝试计算过去三个月内从以下数据出现不止一次的不同会计数量;因为查询的结果我想要2,因为test1@gmail.com和test2@gmail.com出现的次数超过1次。

accountid         purchase  requesttime
test1@gmail.com   150       2017-01-01
test2@gmail.com   100       2017-01-01
test1@gmail.com   100       2017-01-01
test1@gmail.com   200       2017-01-01
test2@gmail.com   240       2017-01-01
test1@gmail.com   210       2017-01-01
test3@gmail.com   4         2017-01-01
test4@gmail.com   60        2017-01-01

2 个答案:

答案 0 :(得分:1)

我认为你需要两个级别的聚合。第一个返回符合条件的电子邮件:

select n.account_id, count(*) as cnt
from ndsbulkstorage22 n
where requesttime >= CURRENT_DATE - interval 3 month
group by accountid
having count(*) > 1;

然后您可以将其用作子查询:

select count(*)
from (select n.account_id, count(*) as cnt
      from ndsbulkstorage22 n
      where requesttime >= CURRENT_DATE - interval 3 month
      group by accountid
      having count(*) > 1
     ) n;

答案 1 :(得分:-1)

此查询将在请求时间和某个购买字段前3个月显示结果。

<强> MYSQL

select accountid,sum(purchase) as your_sum,requesttime from tbl_sum 
where requesttime <=DATE_ADD(requesttime,INTERVAL -3 month) GROUP BY accountid,requesttime

<强> MSQL

select accountid,sum(purchase) as your_sum,requesttime from tbl_sum 
where requesttime <=DATEADD(month,-3,requesttime) GROUP BY accountid,requesttim