2

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?

Seb
  • 21
  • 2

1 Answers1

3

DISTINCT ON might solve your issue.

 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

Find the official documentation here.

Community
  • 1
  • 1
Joost Döbken
  • 3,450
  • 2
  • 35
  • 79