Sql 确定每天导致匹配的右击次数百分比的查询

Sql 确定每天导致匹配的右击次数百分比的查询,sql,join,Sql,Join,如何找到每天导致匹配的正确刷卡次数的百分比。当用户A右击用户B,用户B右击用户A时,匹配发生 以下是示例数据: swiping_user_id swiped_on_user_id swipe_at swipe_type 1 1958315 7247259 2015-03-15 00:01:05 right 2 5823050 8732832 2014-06-10 05:12:

如何找到每天导致匹配的正确刷卡次数的百分比。当用户A右击用户B,用户B右击用户A时,匹配发生

以下是示例数据:

swiping_user_id   swiped_on_user_id      swipe_at            swipe_type
1 1958315            7247259         2015-03-15 00:01:05      right
2 5823050            8732832         2014-06-10 05:12:05      left
3 7948392            6767291         2015-08-10 12:45:01      right

此查询将为您提供导致匹配的刷卡次数:

select count(*) matchedSwipes
from SwipeTable st1
join SwipeTable st2 on 
st1.swiping_user_id = st2.swiped_on_user_id and
st2.swiping_user_id = st1.swiped_on_user_id and
st1.swipe_type = st2.swipe_type
where s1.swipe_type = 'right'

然后,只需获得刷卡总数,并将匹配的刷卡数除以该总数。

如果您需要该比率,则可以执行以下操作:

select count(*) as num_right_swipes,
       count(st2.swipe_type) as num_matches,
       count(st2.swipe_type) * 1.0 / count(*) as ratio
from SwipeTable st1 left join
     SwipeTable st2
     on st2.swiping_user_id = st1.swiped_on_user_id and
        st2.swiped_user_id = st1.swiping_on_user_id and
        st2.swipe_type = st1.swipe_type
where s2.swipe_type = 'right';

这假设刷卡是唯一的(即,不是A对B的两次“正确”刷卡)。如果不是这样,您应该问一个新问题并解释如何处理重复项。

您使用的是什么RDBMS?SQL Server?MySql?谢谢你的解决方案,Michal。这是实践测试的问题之一。因此,任何类型的RDBMS都可以。我只是想看看这个查询的逻辑。