我已经使用您的结构创建了一些数据,这些数据将生成一些示例输出,如果您愿意,可以复制并粘贴到 SSMS 中。
declare @consumer_initiations table ([Program Quarter] int null, event_name varchar(100) null, consumer varchar(50) null)
insert into @consumer_initiations ([Program Quarter], event_name, consumer) values (1, 'Event 1', 'Byrd')
insert into @consumer_initiations ([Program Quarter], event_name, consumer) values (1, 'Event 2', 'Plane')
insert into @consumer_initiations ([Program Quarter], event_name, consumer) values (2, 'Event 3', 'Train')
insert into @consumer_initiations ([Program Quarter], event_name, consumer) values (3, 'Event 4', 'Stuff')
insert into @consumer_initiations ([Program Quarter], event_name, consumer) values (1, 'Event 5', 'Plane')
select [Program Quarter], event_name, consumer
from @consumer_initiations
where [Program Quarter] = 1 --and consumer = 'Byrd, Victoria Lynn'
group by [Program Quarter], event_name, consumer
having count
(distinct event_name) > 1
select [Program Quarter], event_name, consumer
from @consumer_initiations
where [Program Quarter] = 1
-- Possibly gets more information than needed
select consumer, [Program Quarter], count(event_name) as event_count
from @consumer_initiations
where [Program Quarter] = 1
group by [Program Quarter], consumer
having COUNT(event_name) > 1
-- Just displays consumers with more than one event
select consumer, event_count from
(
select [Program Quarter], count(event_name) as event_count, consumer
from @consumer_initiations
where [Program Quarter] = 1
group by [Program Quarter], consumer
having COUNT(event_name) > 1
) as subq
结果
Program Quarter event_name consumer
--------------- ---------------------------------------------------------------------------------------------------- --------------------------------------------------
(0 row(s) affected)
Program Quarter event_name consumer
--------------- ---------------------------------------------------------------------------------------------------- --------------------------------------------------
1 Event 1 Byrd
1 Event 2 Plane
1 Event 5 Plane
(3 row(s) affected)
consumer Program Quarter event_count
-------------------------------------------------- --------------- -----------
Plane 1 2
(1 row(s) affected)
consumer event_count
-------------------------------------------------- -----------
Plane 2
(1 row(s) affected)