简体   繁体   中英

Sql Count Excluding Similar Rows

I have a sql query that is counting the number of times an ID appears in the table inside a date range

    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

Now the problem is if a member registers for this year and the next year at the same time it is counting them twice.(As it should) BUT for this case I want to filter out by the event column and say if they are registered for the same event do not count them twice. Does this make sense? Sorry I am new to this. Let me know how I can improve.

I guess what Im trying to do is something like

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

Thank you

You simply need to Count(Distinct...) on event_number , in an id group. Also event != event in Where clause will always return false , so you would not get any result.

Also, read: Why is SELECT * considered harmful?

And, SELECT list is not in GROUP BY clause and contains nonaggregated column .... incompatible with sql_mode=only_full_group_by

Try the following:

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

You can apply DISTINCT for "MemberId" column

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 

I am guessing that id is the member id. And you want to count events. This would suggest:

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;

Note that I fixed the group by and select so the columns are compatible.

I think this is

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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