开发者

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    | 开发者_如何学Pythonamount
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.

p.s. 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜