altandogan
altandogan

Reputation: 1285

Selected columns that are not in group by

I am a quetions about SQL. For example i have a table like this

Name    Surname Price   Adress
john    smith   100     adress123
alex    martin  200     adress2
john    smith   300     adress123

And i want to group this records which name is same.And this records prices must be sum()
Generally i write query like this

SELECT SUM(PRICE),NAME AS TOTAL_PRICE  FROM TABLE1 A GROUP BY A.NAME

But when i want to select other columns i should be group by like this

... group by A.NAME,A.SURNAME,A.ADRESS

I want select this columns without group by. I want to ask what is the best way selecting other columsn without using group by condition?

I am waiting this result

200 ALEX    MARTIN adress2
210 JOHN    SMITH  adress123

but i don't want to group by surname and adress column

Upvotes: 0

Views: 50

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269943

You can get an arbitrary value from the rest of the columns by using MIN() or MAX():

select sum(price) as total_price, name, max(surname) as surname,
        max(address) as address
from table1 a
group by a.name;

Upvotes: 1

Related Questions