我想合并两个选项以生成一个用于PHP的查询。 每个用户报告时间,这个时间是正常时间(加班= 0)或加班(加班= 1)。
SELECT username,
userlastname,
SUM(time0 + time1 + time2 + time3 + time4 + time5 + time6),
userid,
overtime
FROM users, time
WHERE timeyear = $y
AND timeproid = $proid
AND userid = timeuserid
AND timeweek = $week
GROUP BY userlastname, username, userid, overtime
我有一个显示的表,每个用户有两行,一个用于加班时间,一个用于正常时间。我选择加班,因为如果超时= 0显示超时时间为0,则显示超时为SUM(time0 + time1 + time2 + time3 + time4 + time5 + time6)
有什么办法可以合并两者吗?试试这个link:它现在看起来如何。我希望6和5.5结合使11.5和5.5(加时)保持为5.5
答案 0 :(得分:1)
你可以这样做:
SELECT username,
userlastname,
SUM(CASE WHEN overtime = 0 THEN
time0 + time1 + time2 + time3 + time4 + time5 + time6
ELSE 0 END) AS normaltime,
userid,
SUM(overtime) AS overtime
FROM users, time
WHERE timeyear = $y
AND timeproid = $proid
AND userid = timeuserid
AND timeweek = $week
GROUP BY userlastname, username, userid;
这应该给你加班的“加班”总和,以及其他时间的总和为“正常时间”。如果我理解正确的话,你会把加班时间记录到加班栏中,而在其他地方记录加班时间。
相反,如果你使用加班作为“标志”,意味着“时间0现在超时”,那么你需要这样写:
SELECT username,
userlastname,
SUM(CASE WHEN overtime = 0 THEN
time0 + time1 + time2 + time3 + time4 + time5 + time6
ELSE 0 END) AS normaltime,
userid,
SUM(CASE WHEN overtime != 0 THEN
time0 + time1 + time2 + time3 + time4 + time5 + time6
ELSE 0 END) AS overtime,
FROM users, time
WHERE timeyear = $y
AND timeproid = $proid
AND userid = timeuserid
AND timeweek = $week
GROUP BY userlastname, username, userid;
答案 1 :(得分:0)
您可以使用CASE WHEN / THEN END语法在查询中执行条件语句。
SELECT u.username, u.userlastname, CASE WHEN t.overtime = 1 THEN SUM(t.time0 + t.time1 + t.time2 + t.time3 + t.time4 + t.time5 + t.time6) ELSE 0 END as overtime, u.userid
FROM users u
LEFT JOIN time t ON(u.userid=t.timeuserid)
WHERE t.timeyear = $y AND t.timeproid = $proid AND t.timeweek = $week
GROUP BY u.userlastname, u.username, u.userid, t.overtime
答案 2 :(得分:0)
否则联盟会满足您的需求(当然不是最佳的绩效导向答案)?
SELECT username,
userlastname,
SUM(time0 + time1 + time2 + time3 + time4 + time5 + time6) as overtime,
userid,
overtime
FROM users, time
WHERE timeyear = $y
AND timeproid = $proid
AND userid = timeuserid
AND timeweek = $week
AND overtime=1
GROUP BY userlastname, username, userid
union
SELECT username,
userlastname,
0 as overtime,
userid,
overtime
FROM users, time
WHERE timeyear = $y
AND timeproid = $proid
AND userid = timeuserid
AND timeweek = $week
AND overtime=0
GROUP BY userlastname, username, userid