Name Username Day worked Time period
----------------------------------------------
John Doe john Sunday 8
Tom tom Monday 10
Jane Doe jane Tuesday 5
John Doe john Friday 9
查询:
SELECT username FROM table WHERE (day_worked='Sunday' AND time_period>5) AND (day_worked='Friday' and time_period>8)
我在这里申请两个栏目的条件,周日工作时间超过5小时,周五工作时间超过8小时。显然,John Doe(用户名:john)符合条件,应该输出。
然而,这不会返回任何东西。可能是我使用的逻辑是错误的。有什么想法吗?
答案 0 :(得分:2)
你可以通过一些交叉制表魔术来做到这一点。首先,在周日和周五之间交叉制表所有用户:
SELECT
username,
SUM(CASE WHEN `Day worked` = 'Sunday' THEN `Time Period` END) As Sunday,
SUM(CASE WHEN `Day worked` = 'Friday' THEN `Time Period` END) AS Friday
FROM table
GROUP BY username
此查询将产生以下内容:
username Sunday Friday
-------- ------ ------
jane NULL NULL
john 8 9
tom NULL NULL
通过将此结果推送到子查询中,您可以轻松地选出周日工作时间超过5小时且周五工作时间超过8小时的人员:
SELECT username
FROM (
SELECT
username,
SUM(CASE WHEN `Day worked` = 'Sunday' THEN `Time Period` END) As Sunday,
SUM(CASE WHEN `Day worked` = 'Friday' THEN `Time Period` END) AS Friday
FROM table
GROUP BY username
) SunFri
WHERE SunFri.Sunday > 5 AND SunFri.Friday > 8
答案 1 :(得分:1)
SELECT username
FROM table
WHERE (day_worked='Sunday' AND time_period>5)
OR (day_worked='Friday' and time_period>8)
GROUP
BY username
HAVING COUNT(*) = 2
答案 2 :(得分:0)
您可以检查此查询是否为您提供了所需的结果
SELECT username FROM table
INNER JOIN table T2 ON table.Username = T2.Username AND (day_worked='Friday' and time_period>8)
WHERE (day_worked='Sunday' AND time_period>5)
最好发布一个sqlfiddle供我们使用。