我有一个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
谢谢
答案 0 :(得分:1)
您只需要在event_number
组中的id
上Count(Distinct...)
。此外,Where子句中的event != event
将始终返回false
,因此您不会得到任何结果。
此外,请阅读:Why is SELECT * considered harmful?
尝试以下操作:
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
答案 1 :(得分:0)
您可以将DISTINCT应用于“ MemberId”列
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
答案 2 :(得分:0)
我猜测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
,以使各列兼容。
答案 3 :(得分:0)
我认为这是
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