我試圖使用UNION獲取兩個具有相同字段的查詢。我需要的是重複的行被刪除,但它們不是。這兩個查詢都包含國家,Idcustomer,類型和成本。下面我舉一個例子:使用UNION刪除重複的行
Country | Idcustomer | Type | Cost
Brazil 123 1 3,2
Brazil 212 1 4,1
Country | Idcustomer | Type | Cost
Brazil 123 2 5,5
Brazil 212 2 4,3
Brazil 543 2 4,2
提取後,我需要的是,如果Idcustomer是在兩個查詢,優先於第一個。我認爲聯盟會解決這個問題,因爲它會刪除重複的值,但不是。
Country | Idcustomer | Type | Cost
Brazil 123 1 3,2
Brazil 212 1 4,1
Brazil 543 2 4,2
任何想法?非常感謝!
SELECT A.*
FROM (
SELECT Country, Idcustomer, type, cost
FROM qry_cost
WHERE type = 1
) AS A,
(
SELECT qry_cost.Idcustomer, MIN(qry_cost.cost) AS cost_min
FROM qry_cost
WHERE type = 1
GROUP BY qry_cost.Idcustomer
) AS B
WHERE A.Idcustomer = B.Idcustomer
AND A.cost = B.cost
UNION
SELECT A.*
FROM (
SELECT Country, Idcustomer, type, cost
FROM qry_cost
WHERE type = 2
) AS A,
(
SELECT qry_cost.Idcustomer, MIN(qry_cost.cost) AS cost_min
FROM qry_cost
WHERE type = 2
GROUP BY qry_cost.Idcustomer
) AS B
WHERE A.Idcustomer = B.Idcustomer
AND A.cost = B.cost;
你能發佈您的查詢嗎? –
您的數據不包含重複的行。 「提取後,我需要的是,如果Idcustomer同時處理這兩個問題,請優先考慮第一個問題,我認爲UNION正在解決這個問題」......不。這不是'工會'的工作方式。完全一樣。 – 2017-02-09 17:52:59
SELECT A. * FROM(SELECT Country,Idcustomer,type,cost FROM qry_cost WHERE type = 1)AS A,(SELECT qry_cost.Idcustomer,MIN(qry_cost.cost)AS cost_min FROM qry_cost WHERE type = 1 GROUP BY qry_cost.Idcustomer )AS B WHERE A.Idcustomer = B.Idcustomer AND A.cost = B.cost UNION SELECT A. * FROM(SELECT Country,Idcustomer,type,cost FROM qry_cost WHERE type = 2)AS A,(SELECT qry_cost。 Idcustomer,MIN(qry_cost.cost)AS cost_min FROM qry_cost WHERE type = 2 GROUP BY qry_cost.Idcustomer)AS B WHERE A.Idcustomer = B.Idcustomer AND A.cost = B.cost; –