1

我想合并两个选择以进行一个查询以在 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)

有什么办法可以将两者合并吗?试试这个链接:它现在的样子。我希望将 6 和 5.5 组合成 11.5,并将 5.5(加班)保留为 5.5

看到这个

4

3 回答 3

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;

这应该给你加班时间的总和,以及其他时间的总和作为“正常时间”。如果我理解正确,您将加班时间记录在加班一栏中,而在其他地方记录不加班时间。

相反,如果您使用超时作为“标志”,表示“time0 现在超时”,那么您需要这样编写:

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;
于 2012-07-19T15:25:51.390 回答
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
于 2012-07-19T14:58:12.587 回答
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
于 2012-07-19T15:35:23.573 回答