嗨,我是sql世界的新手,但努力让一些基础工作。
我有一组看起来像这样的数据:
Table name: Sample
PROJECT WORK ORDER AMOUNT
-----------------------------------------
111 a 100
222 b 200
111 c 300
444 d 400
111 e 500
666 f 600
我希望它最终看起来像这样:
Table name: Sample
PROJECT WORK ORDER AMOUNT PROJECT AMOUNT
--------------------------------------------------------
111 e 500 900
111 c 300 900
111 a 100 900
666 f 600 600
444 d 400 600
222 b 200 200
按项目总金额
排序分组对我不起作用,因为它将所有项目分组为一个,所以我看不到“Project 111”的3个工单行
PROJECT WORK ORDER AMOUNT
-----------------------------------------
111 a 900
222 b 200
444 d 400
666 f 600
排序不起作用,因为我无法根据最大的项目价值对其进行排序
Table name: Sample
PROJECT WORK ORDER AMOUNT
-----------------------------------------
666 f 600
111 e 500
444 d 400
111 c 300
222 b 200
111 a 100
我的另一个想法是,如果我可以创建另一个列“项目金额”,根据“项目”列中的值计算项目总数,然后我可以轻松地按项目金额对其进行排序,以达到所需的格式
Table name: Sample
PROJECT WORK ORDER AMOUNT PROJECT AMOUNT
--------------------------------------------------------
111 e 500 900
111 c 300 900
111 a 100 900
666 f 600 600
444 d 400 600
222 b 200 200
但我正在努力如何获得列“项目金额”来计算所有项目的总价值,并将它们显示在出现在同一项目编号的任何行上。
有任何建议吗?
答案 0 :(得分:4)
select *
, sum(amount) over (partition by project) as ProjAmount
, row_number() over
from YourTable
order by
ProjAmount desc
要仅选择金额最高的前两个项目,您可以使用dense_rank
:
select *
from (
select *
, dense_rank() over (order by ProjAmount desc) as dr
from (
select *
, sum(amount) over (partition by project) as ProjAmount
from YourTable
) WithProjAmount
) WithDenseRank
where dr < 3
order by
ProjAmount desc
答案 1 :(得分:1)
具有普通SQL子查询的版本
SELECT s.*,
(SELECT SUM(Amount) FROM Sample WHERE Project = s.Project) ProjectAmount
FROM Sample s
ORDER BY ProjectAmount DESC
<强> SQLFiddle 强>
答案 2 :(得分:0)
SELECT a.project ,
a.work ,
a.amount ,
b.proj_amount
FROM project A
JOIN ( SELECT SUM(amount) proj_amount ,
project
FROM project
WHERE project = project
GROUP BY project
) b ON a.project = b.project
ORDER BY proj_amount DESC ,
amount DESC