0

我对 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
  

报告表

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 的团队中的总用户

未发送计数:总计数 - 发送计数

什么是有效的方法?

4

3 回答 3

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

请注意,您的预期结果并不反映您的数据。根据您的数据得出的结果应该是:

+--------+------------+------------+--------------+
| 团队 | 总数 | 发送计数 | 未发送计数 |
+--------+------------+------------+--------------+
| 1 | 2 | 1 | 1 |
| 2 | 1 | 1 | 0 |
+--------+------------+------------+--------------+
于 2012-04-10T06:02:32.177 回答
0

如果没有桌子来尝试这个,我无法检查这是否可行,但这应该能让你大部分时间:

SELECT TeamID, count(userID) as "Total count", Sum(IsSend) as "Send Count" FROM MemberTable JOIN ReportTable ON UserID GROUP BY TeamID; 
于 2012-04-10T06:06:18.210 回答
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

在这里尝试:https ://data.stackexchange.com/stackoverflow/query/66347

于 2012-04-10T06:16:47.133 回答