我有一個需要查詢兩次,產生這種格式產生結果的單一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的替代方法,但查詢總是失敗。
,什麼是混亂呢?你正在使用'COUNT(*)'來計算兩者,所以如果值不一樣,我會非常驚訝。 –