使用UNION删除重复的行

时间:2017-02-09 17:50:47

标签: sql ms-access

我尝试使用UNION获取具有相同字段的两个查询。我需要的是删除重复的行,但它们不是。两个查询都包含Country,Idcustomer,Type和Cost。下面我展示一个例子:

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同时处理两个查询,请优先考虑第一个查询。我认为UNION将解决这个问题,因为它删除了重复的值......但事实并非如此。

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; 

2 个答案:

答案 0 :(得分:0)

       create  table #Country1
(
    country nvarchar(50),
    idcustomer int, 
    type int, 
    cost decimal(19,6)

)
    create table #Country2
    (
        country nvarchar(50),
        idcustomer int, 
        type int, 
        cost decimal(19,6)

    )
    create table #Country3
    (
        country nvarchar(50),
        idcustomer int, 
        type int, 
        cost decimal(19,6)

    )


    insert into #Country1(country,idcustomer,type,cost) Values('Brazil', 123,1,3.2)

    insert into #Country2(country,idcustomer,type,cost) VALUEs  ('Brazil', 212,1,4.1)

    insert into #Country3 (country,idcustomer,type,cost)VALUES ('Brazil', 123,2,5.5)
    insert into #Country3(country,idcustomer,type,cost)VALUEs  ('Brazil', 212,2,4.3)
    insert into #Country3 (country,idcustomer,type,cost)VALUES ('Brazil', 543,2,4.2)
 -- YOUR ANSWER IS AS FOLLOWS    
     select * from #Country1 
    UNION 
    select * from #Country2
    UNION 
    select * from #Country3 where cost= 4.2 


-- DROP IT     
    DROP TABLE #Country1
    DROP TABLE #Country2
    DROP TABLE #Country3


--RESULT if you run ABOVE QUERY 

Reult

答案 1 :(得分:0)

我认为您需要确定要在“外部”查询中保留哪些记录。通过这个,我的意思是将它全部包装在一个新层中。类似的东西:

mv