2015-05-30 63 views
1
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

嘗試:SELECT用戶名FROM表WHERE(天_worked ='Sunday'AND time_period> 5)OR(day_worked ='Friday'and time_period> 8) – Dharmang

+0

@Dharmang:它必須是AND耦合的。我需要週日和週五都在單獨工作的用戶。 –

+0

@Dharmang他需要兩個。 OR會匹配任何一種情況。我不認爲這是他正在尋找的。我不認爲他的榜樣是最好的例子。他可以多次使用相同的用戶名,適用於不同的日子和時間。他想知道世界衛生組織星期五工作超過8小時,星期天工作超過5小時,而不是任何一天。 –

回答

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 
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我們一起工作。

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