简体   繁体   English

SQL select from table where key in array group by column

[英]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.但不能作为group by还需要列出其他列名,最终不会根据需要合并两行。

ps I'm using postgresql ps 我正在使用 postgresql

If you just want those 2 fields you can use the Aggregate SUM():如果您只想要这两个字段,您可以使用 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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