排除类似行的sql计数

6l7fqoea  于 2021-06-20  发布在  Mysql
关注(0)|答案(4)|浏览(320)

我有一个sql查询,它计算一个id在一个日期范围内出现在表中的次数

SELECT *,COUNT( id) AS member_count FROM members_history 
where date_registered > '2018-09-01' 
AND date_registered < '2018-12-31' 
GROUP BY id ORDER BY last_name,first_name ASC

现在的问题是,如果一个成员同时为今年和明年注册,那么它将对他们进行两次计数(这是应该的),但是对于这种情况,我想按事件列过滤掉,并说如果他们为同一事件注册,就不要对他们进行两次计数。这有道理吗?对不起,我是新来的。让我知道怎样才能提高。
我想我要做的是

SELECT *,
       COUNT( id) AS member_count 
FROM members_history 
where date_registered > '2018-09-01' AND 
      date_registered < '2018-12-31' AND 
      event!= event 
GROUP BY id 
ORDER BY last_name,first_name ASC

谢谢您

agxfikkp

agxfikkp1#

你只需要 Count(Distinct...)event_number ,在 id 组。也 event != event 在where子句中总是返回 false ,所以不会得到任何结果。
另外,阅读:为什么select*被认为是有害的?
而且,select list不在GROUPBY子句中,并且包含未聚合的列。。。。与sql不兼容\u mode=only \u full \u group by
请尝试以下操作:

SELECT id, 
       firstname, 
       lastname, 
       COUNT(DISTINCT event_number) AS member_count 
FROM members_history 
where date_registered > '2018-09-01' AND 
      date_registered < '2018-12-31' 
GROUP BY id, firstname, lastname  
ORDER BY last_name,first_name ASC
tct7dpnv

tct7dpnv2#

我猜是的 id 是成员id。您要对事件进行计数。这意味着:

select id, last_name, first_name, count(distinct event_id) AS num_events 
from members_history 
where date_registered > '2018-09-01' and date_registered < '2018-12-31' 
group by id, last_name, first_name
order by last_name, first_name asc;

注意,我修复了 group by 以及 select 所以这些列是兼容的。

inn6fuwd

inn6fuwd3#

您可以为“memberid”列应用distinct

SELECT COUNT( DISTINCT  MemberId) AS member_count 
FROM members_history 
where date_registered > '2018-09-01' AND 
      date_registered < '2018-12-31' AND 
      event!= event 
GROUP BY id
ttisahbt

ttisahbt4#

我想这是

SELECT id,event,COUNT(*) AS member_count 
    FROM members_history 
    where date_registered > '2018-09-01' AND 
          date_registered < '2018-12-31' AND 

    GROUP BY id,event 
    having count (event)=1

相关问题