SQL从表中选择数组中的键按列

时间:2011-06-01 15:18:28

标签: sql postgresql

给出一个表格账单

# 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

4 个答案:

答案 0 :(得分:3)

如果您只想要这两个字段,可以使用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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

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

答案 3 :(得分:1)

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