我有一张这样的桌子
itm_nbr Owner Cost
-------- --------- ---------
1 Gary $5
2 Henry $12
3 Gary $3
4 Rob $5
5 Rob $31
6 Henry $20
7 Gary $1
我想查询以找到每个所有者的项目数及其总成本的总和,从而得出以下结果:
ItemCount Owner Cost
-------- --------- ---------
3 Gary $9
2 Henry $22
2 Rob $36
我尝试了以下查询
SELECT count(itm_nbr), owner, sum(cost)
FROM table
GROUP BY Owner
ORDER BY Cost
答案 0 :(得分:1)
您快到了。到目前为止,您的查询无效,因为您正尝试对汇总的列(cost
)进行排序。
您要对费用总和进行排序:
select
count(itm_nbr),
owner,
sum(cost)
from table
group by owner
order by sum(cost)
或者更好的是,您可以为所有列添加别名,并在order by
子句中使用别名。
select
count(itm_nbr) cnt_item_nbr,
owner,
sum(cost) sum_cost
from table
group by owner
order by sum_cost