sql - Do not include select columns in group by -


here tables(including relevant columns)

table: carts address_id - integer  table: addresses name - varchar phone - varchar  table: orders order_number - integer (this foreign key cart table) 

i want fetch phone number of customers have ordered once, constructed following query

select addresses.phone  orders     inner join carts on orders.order_number = carts.id     inner join address on carts.address_id = addresses.id  group addresses.phone  having count(orders.*) = 1; 

this works great! need select customer name & order number , updated select statement to

select addresses.phone, addresses.name, orders.order_number ... 

now, postgres urges me include these columns in group by clause not return me desired result.

i tried using subquery following seems me desired result

select addresses.phone, (select ad.name addresses ad ad.phone = addresses.phone) ... 

but using subquery way go ? or there simpler/optimal way ?

you can achieve window function doesn't require grouped:

select * (   select addresses.phone, addresses.name, orders.order_number,           count(orders.order_number) on (partition addresses.phone) cnt   orders       inner join carts on orders.order_number = carts.id       inner join address on carts.address_id = addresses.id  ) t  cnt = 1; 

Comments

Popular posts from this blog

How to connect android app to App engine -

gcc - MinGW's ld cannot perform PE operations on non PE output file -

php - display validation error message next to the textbox in codeigniter -