簡體   English   中英

將2個SQL查詢合並到同一張表中的1個中

[英]Combine 2 SQL queries into 1 from same table

我有一個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替代方法,但是查詢始終失敗。

使用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 

我將推測pmpricematch相同,並且您確實需要條件聚合:

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM