给一张桌子账单

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

和一个表用户
# users
id  | name
1   | John Doe
2   | Mike Marley
3   | Bill Mickane

当我执行查询时
select * from bills where user_id in (1,2) order by name, amount desc

我明白了
# bills
id  | name    | amount  | user_id
2   | gopper  | 200     | 1
3   | jumper  | 150     | 2
1   | jumper  | 100     | 1

但我想要的是(和所有其他专栏)
# bills
name    | amount
gopper  | 200
jumper  | 250

这是怎么做到的?
我很想用
select * from bills where user_id in (1,2) group by name order by name, amount desc

但是不能,因为group by还需要列出其他列名,并且最终无法按需要合并这两行。
p.s.我在用postgresql

最佳答案

如果您只需要这两个字段,那么可以使用Aggregate SUM():

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

然而,假设你想要的不止这两个领域。。。
嵌套查询可以帮助您解决问题。
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

关于sql - SQL从表中进行选择,其中键按列分组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6203545/

10-09 00:50