2016-03-04 106 views
2

我有一個需要查詢兩次,產生這種格式產生結果的單一MySQL表:結合2個SQL查詢到1,從同一個表

+------------+----------+-------------------+ 
| Supplier | Requests | Requests_Approved | 
+------------+----------+-------------------+ 
| Supplier 1 |  50 |    45 | 
| Supplier 2 |  75 |    63 | 
| Supplier 3 |  48 |    32 | 
| Supplier 4 |  104 |    87 | 
+------------+----------+-------------------+ 

到目前爲止,我已經試過如下:

SELECT Supplier, COUNT(*) AS Requests, COUNT(*) AS Requests_Approved 
FROM pricematch 
WHERE Date_Received >= '2015-01-01' 
AND Date_Received <= '2015-12-31' 
AND PM_Level = 'Escalation' 
GROUP BY Supplier 
UNION 
SELECT Supplier, COUNT(*) AS Requests, COUNT(*) AS Approved 
FROM pricematch 
WHERE Date_Time_Received >= '2015-01-01' 
AND Date_Time_Received <= '2015-12-31' 
AND PM_Level = 'Escalation' 
AND Matched = 'Yes' 
GROUP BY Supplier 
ORDER BY Requests DESC 
LIMIT 20 

哪產生以下結果表,並在兩者的列數相同的結果:

+------------+----------+-------------------+ 
| Supplier | Requests | Requests_Approved | 
+------------+----------+-------------------+ 
| Supplier 1 |  50 |    50 | 
| Supplier 2 |  75 |    75 | 
| Supplier 3 |  48 |    48 | 
| Supplier 4 |  104 |    104 | 
+------------+----------+-------------------+ 

我在這裏查看了很多類似的問題/答案,並嘗試了使用LEFT JOIN和INNER JOIN的替代方法,但查詢總是失敗。

+0

,什麼是混亂呢?你正在使用'COUNT(*)'來計算兩者,所以如果值不一樣,我會非常驚訝。 –

回答

3

使用Conditional Aggregate

SELECT Supplier, 
     Count(*) AS Requests, 
     Count(CASE 
       WHEN Matched = 'Yes' THEN 1 
      END) AS Approved 
FROM pm 
WHERE Date_Received >= '2015-01-01' 
     AND Date_Received <= '2015-12-31' 
     AND PM_Level = 'Escalation' 
GROUP BY Supplier 
+0

完美!感謝您及時的回覆。將在8分鐘內標記爲正確答案(如第一次答覆):-) – jimbo80

2

我要推測pm相同pricematch和你真的想有條件聚集:

SELECT Supplier, COUNT(*) AS Requests, 
     SUM(Matched = 'Yes') AS Approved 
FROM pricematch pm 
WHERE Date_Time_Received >= '2015-01-01' AND 
     Date_Time_Received <= '2015-12-31' AND 
     PM_Level = 'Escalation' 
GROUP BY Supplier 
ORDER BY Requests DESC 
LIMIT 20; 
+0

是的確 - 問題用正確的表名稱更新。感謝您及時的回覆! :-) – jimbo80