[英]Mysql users compare to itself
首先,这在SQL中不是很自然的事情。 但是有可能。 要创建交叉引用表,您需要生成行,然后填充列:
select user_id_a,
sum(case when user_id_b = 1 then hours_oncall else 0 end) as user_1,
sum(case when user_id_b = 2 then hours_oncall else 0 end) as user_2,
sum(case when user_id_b = 3 then hours_oncall else 0 end) as user_3
from ((select user_id_a from t
) union
(select user_id_b from t
)
) u left join
t
on t.user_id_a = u.user_id_a
group by u.user_id_a;
在普通的SQL中,您不能有动态的列数来调整用户数,尽管在代码中您可以生成执行此操作的SQL。 但是我认为您最好只获得显示谁欠谁多少小时的行,并像代码中的数据透视表一样转换数据。
为了获得基本数据,假设您的表名为hours_oncall:
select ower,owed,sum(hours_oncall) hours
from (
select user_id_a ower,user_id_b owed,hours_oncall from hours_oncall
union all
select user_id_b,user_id_a,-hours_oncall from hours_oncall
) hours_oncall_union
group by 1,2
having hours>0;
对于您的样本数据,返回:
+------+------+-------+
| ower | owed | hours |
+------+------+-------+
| 1 | 2 | 6 |
| 2 | 3 | 2 |
+------+------+-------+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.