简体   繁体   中英

SQL select from table where key in array group by column

given a table bills

# bills
id  | name    | amount  | user_id
1   | jumper  | 100     | 1
2   | gopper  | 200     | 1
3   | jumper  | 150     | 2
4   | blobber | 300     | 3

and a table users

# users
id  | name
1   | John Doe
2   | Mike Marley
3   | Bill Mickane

when I perform the query

select * from bills where user_id in (1,2) order by name, amount desc

I get

# bills
id  | name    | amount  | user_id
2   | gopper  | 200     | 1
3   | jumper  | 150     | 2
1   | jumper  | 100     | 1

but what I want is (and all other columns)

# bills
name    | amount
gopper  | 200   
jumper  | 250   

how would this be achived?

I'm tempted to use

select * from bills where user_id in (1,2) group by name order by name, amount desc

but can't as the group by would also need to list the other column names and end up not merging the two rows as desired.

ps I'm using postgresql

If you just want those 2 fields you can use the Aggregate SUM():

 SELECT 
          name, 
          SUM(amount) 
     FROM 
          bills 
     WHERE 
          user_id IN (1,2) 
     GROUP BY 
          name 
     ORDER BY 
          name, 
          amount

However, assume you wanted more then just those two fields... nested queries should help you out.

SELECT
 m.id, m.name, t.userId, t.amount 
FROM Bills m
 INNER JOIN
 (
   SELECT
          user_id as userID,
          SUM(amount) as amount
   FROM
          bills
   GROUP BY user_id
 ) t
ON t.UserID = m.UserID
SELECT 
    name, SUM(amount) 
FROM 
    bills 
WHERE 
    user_id IN (1,2) 
GROUP BY 
    name 
ORDER BY 
    name, amount DESC
SELECT name, SUM(amount) as amount
FROM bills where user_id IN (1,2) 
GROUP BY name
ORDER BY name, amount DESC
select name, sum(amount) as amount
from bills where user_id in (1,2) 
group by name 
order by name, amount desc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM