我在试着概述谁欠谁随叫随到的时间。在我的桌子下面。

所以用户2为用户1做了9个小时。但是用户1为用户2做了3个小时,所以用户1应付的总时间是6个小时。并且用户2欠用户3,2个待机时间。如何在Mysql中制作所有用户的对照表?

发布于 2016-12-09 10:32:46
首先,在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;发布于 2016-12-10 03:17:45
在普通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 |
+------+------+-------+https://stackoverflow.com/questions/41052164
复制相似问题