我是sql的新手。我需要一些帮助来生成夏日信息
会员表
MonthID | UserID | TeamID
-----------------------------
1 | 1 | 1
1 | 2 | 1
1 | 3 | 1
1 | 4 | 1
1 | 5 | 2
1 | 6 | 2
1 | 7 | 2
AND
ReportTable
ID* | MonthID | UserID | IsSend
-----------------------------------
1 | 1 | 2 | False
2 | 1 | 3 | True
3 | 1 | 5 | True
我想生成一个像以下
的总结TeamID | Total Count | Send Count | Not Send Count
-----------------------------------------------------------
1 | 4 | 1 | 3
2 | 3 | 1 | 2
总计数:团队中的用户数
发送计数:IsSend = True
的团队中的总用户数不发送计数:总计数 - 发送计数
什么是有效的方式?
答案 0 :(得分:1)
尝试一下:
select mt.teamId, count(*) totalCount,
count(case when rt.isSend = 'True' then 1 end) sendCount,
count(case when rt.isSend != 'True' then 1 end) notSendCount
from memberTable mt
join reportTable rt on mt.userId = rt.userId
group by mt.teamId
请注意,您的预期结果不会反映您的数据。基于您的数据的结果应该是:
+--------+------------+-----------+--------------+ | TEAMID | TOTALCOUNT | SENDCOUNT | NOTSENDCOUNT | +--------+------------+-----------+--------------+ | 1 | 2 | 1 | 1 | | 2 | 1 | 1 | 0 | +--------+------------+-----------+--------------+
答案 1 :(得分:0)
没有表格试试这个,我无法检查这是否有效,但这应该可以帮到你:
SELECT TeamID, count(userID) as "Total count", Sum(IsSend) as "Send Count" FROM MemberTable JOIN ReportTable ON UserID GROUP BY TeamID;
答案 2 :(得分:0)
select MT.TeamID,
count(distinct MT.UserID) as "Total Count",
count(distinct case when RT.IsSend = 1 then MT.UserID end) as "Send Count",
count(distinct MT.UserID) - count(distinct case when RT.IsSend = 1 then MT.UserID end) as "Not Send Count"
from MemberTable as MT
left outer join ReportTable as RT
on MT.MonthID = RT.MonthID and
MT.UserID = RT.UserID
group by MT.TeamID
结果:
TeamID Total Count Send Count Not Send Count
----------- ----------- ----------- --------------
1 4 1 3
2 3 1 2
在此尝试:http://data.stackexchange.com/stackoverflow/query/66347