我必须在SQL Server中解决以下任务:我必须在以下两个表中的一列上计算不同的时间。
Project
包含来自不同项目的用户的预订。User
包含不同团队的用户成员资格。Result
包含我需要的查询结果。我需要在特定时间段内预订项目的不同团队的用户数量(而不是预订数量)。
使用Count distinct
我可以计算All_Users
列。但是如何计算剩下的?
有人可以给我一个提示吗?
表项目:
Project Date User
-----------------------------
P1 01.02.2017 John
P1 01.02.2017 Mary
P1 01.02.2017 Molly
P2 01.02.2017 John
P2 02.02.2017 Paul
P2 05.02.2017 Bill
P2 06.02.2017 Emily
P3 03.04.2017 Steve
P3 04.04.2017 Steve
P3 05.04.2017 John
表用户:
User Team
-------------
John EXT
Emily BI
Steve BC
Bill NT
Mary EXT
Molly BC
Paul NT
表结果:
Projekt ALL_USERS TEAM_BI-BC-NT TEAM_BI TEAM_BC TEAM_NT TEAM_EXT
--------------------------------------------------------------------
P1 3 1 0 0 0 2
P2 4 3 1 0 2 1
P3 2 1 0 1 0 1
答案 0 :(得分:1)
使用条件聚合:
select p.projekt, count(*) as all_users,
sum(case when team in ('BI', 'BC', 'NT') then 1 else 0 end) as bi_bc_nt_cnt,
sum(case when team = 'BI' then 1 else 0 end) as bi_cnt,
sum(case when team = 'BC' then 1 else 0 end) as bc_cnt,
sum(case when team = 'NT' then 1 else 0 end) as nt_cnt,
sum(case when team = 'EXT' then 1 else 0 end) as ext_cnt
from project p join
user u
on p.user = u.user
group by p.projekt;
根据您的评论,您需要某种distinct
。让我坚持使用相同的结构,并在子查询中执行此操作:
select p.projekt, count(*) as all_users,
sum(case when u.team in ('BI', 'BC', 'NT') then 1 else 0 end) as bi_bc_nt_cnt,
sum(case when u.team = 'BI' then 1 else 0 end) as bi_cnt,
sum(case when u.team = 'BC' then 1 else 0 end) as bc_cnt,
sum(case when u.team = 'NT' then 1 else 0 end) as nt_cnt,
sum(case when u.team = 'EXT' then 1 else 0 end) as ext_cnt
from (select distinct projekt, user
from project p
) p join
user u
on p.user = u.user
group by p.projekt;