Remove column duplicates with union join postgresql

时间:2016-04-04 17:30:12

标签: sql postgresql duplicates

I want to hide duplicate columns in my postgresql select statement. Here is the sql code:

SELECT name, amount, cpu, id 
FROM computersystem, stock 
WHERE cpu=id 
UNION 
SELECT name, amount, ram, id 
FROM computersystem, stock 
WHERE ram=id 
ORDER BY name, amount

And the current output:

Name:AMD Ultimate Overkill amount:2
Name:AMD Ultimate Overkill amount:10
Name:CPU Heavy, Low Graphics amount:2
Name:CPU Heavy, Low Graphics amount:10
Name:Graphics Heavy, Low CPU amount:8
Name:Graphics Heavy, Low CPU amount:10

What I need to get is only 1 of each name

Name:AMD Ultimate Overkill amount:2
Name:CPU Heavy, Low Graphics amount:2
Name:Graphics Heavy, Low CPU amount:8

Is there a quick fix for this?

1 个答案:

答案 0 :(得分:0)

DISTINCT ON可能会解决您的问题。

 SELECT DISTINCT ON (name)
        name,
        amount,
        cpu,
        id
 FROM computersystem, stock 
 WHERE cpu=id 
 UNION SELECT name, amount, ram, id FROM computersystem, stock 
 WHERE ram=id
 GROUP BY name
 ORDER BY name, amount

查找官方文档here

相关问题