我有一个 MySQL 表,需要查询两次才能生成以下格式的结果:
+------------+----------+-------------------+
| 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 的替代方案,但查询总是失败。
最佳答案
使用条件聚合
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
关于mysql - 将同一个表中的 2 个 SQL 查询合并为 1 个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35797195/