我有一个像这样的user
表
FIRSTNAME | LASTNAME | ID |
--------------------------------
James | Hay | 1 |
Other | Person | 2 |
我也有attendance
这样的表
EVENTID | USERID | ATTENDANCE | STATUS |
-----------------------------------------------
1 1 True 3
2 1 False 1
3 1 False 3
1 2 False 1
2 2 True 3
3 2 True 3
基本上,当用户被邀请参加某个活动时,会在attendance
表中添加一行,其中包含事件ID,用户ID,错误出席率和状态0。
状态只是其回复的指标
0 = No Response
1 = Said No
2 = Said Yes
3 = Said yes and seats confirmed
我想从查询这两个表中得到的最终结果非常复杂,我无法弄清楚我需要做什么。
我想得到像这样的结果
NAME | % of saying YES to an RSVP | % of attending after saying yes
-------------------------------------------------------------------------------
James Hay | 66 | 50
Other Person | 66 | 100
我确定你可以弄清楚我是如何获得这些数据但是要解释一下,James Hay对邀请的2/3赛事有3个(是)状态。所以说“是”的百分比是66.在他说“是”的2个中,他只是在参加“是50%”之后参加了1/2%
因为我无法理解这一点,所以在这里的任何推动都会非常受欢迎。
修改
同样重要的是,我希望结果包括数据库中的每个用户,即使它们在attendance
表中有0行。
答案 0 :(得分:2)
select
u.firstname, u.lastname
-- said yes, as percentage
,floor(100.0
* count(case when a.status in (2,3) then 1 end)
/ count(u.id)) yes
-- attended after saying yes, as percentage
,floor(100.0
* count(case when a.status in (2,3) and attendance='true' then 1 end)
/ nullif(count(case when a.status in (2,3) then 1 end),0)) attendance
--,count(u.id) rsvp -- total invites
from users u
left join attendance a on a.userid = u.id
group by u.firstname, u.lastname
注意:对于用户从未收到过邀请的特殊情况,统计信息显示为0%且为NULL。
条款说明:
count(case when a.status in (2,3) then 1 end)
count(u.id)
1
(不重要)count(case when a.status in (2,3) and attendance='true' then 1 end)
答案 1 :(得分:1)
SELECT A.NAME,B.PERCENTAGE_YES_RSVP,B.PERCENTAGE_AFTER_YES
FROM
(
SELECT U.ID AS ID,U.FIRSTNAME+''+U.LASTNAME AS NAME
FROM USERS U
) A,
(
SELECT A.USERID,A.PERCENTAGE_YES_RSVP,B.PERCENTAGE_AFTER_YES
FROM
(
SELECT B.USERID,ROUND((CAST(B.COUNT_YES_RSVP AS FLOAT)/B.TOTAL_COUNT)*100,0) AS PERCENTAGE_YES_RSVP
FROM
(SELECT A.USERID,
SUM(CASE WHEN A.STATUS=3 THEN 1 END)AS COUNT_YES_RSVP,
COUNT(*) AS TOTAL_COUNT
FROM ATTENDANCE A
GROUP BY A.USERID
) B
) A,
(
SELECT C.USERID,(CAST(C.COUNT_AFTER_YES_RSVP AS FLOAT)/C.TOTAL_COUNT)*100 AS PERCENTAGE_AFTER_YES
FROM
(SELECT A.USERID,
SUM(CASE WHEN A.STATUS=3 AND A.ATTENDANCE='TRUE' THEN 1 END)AS COUNT_AFTER_YES_RSVP,
SUM(CASE WHEN A.STATUS=3 THEN 1 END) AS TOTAL_COUNT
FROM ATTENDANCE A
GROUP BY A.USERID
) C
)B
WHERE A.USERID=B.USERID
) B
WHERE A.ID = B.USERID;
答案 2 :(得分:1)
修改强>
哎呀,忘了加入用户:)
select firstname, lastname,
convert(decimal (5, 2), 1. * count(case when status in (2, 3) then 1 end) / count(*) * 100) SaidYes,
convert(decimal (5, 2), 1. * count(case when status in (2, 3) and attendance = 'True' then 1 end) / count(case when status in (2, 3) then 1 end) * 100) ActuallyAttended
from attendance a
join users u on a.userid = u.id
group by firstname, lastname