假设我有一个查询这样的表:
+-------+-----+--------------------+-----+--------------------+
|CODE |CURR |FRONT-END CHARGE |CCY |BACK-END CHARGE |
+-------+-----+--------------------+-----+--------------------+
|002 |AUD |5.25 |PHP | 3.75 |
|002 |AUD |1.75 |USD | 1.25 |
|002 |BGN | 14 |PHP | 8.75 |
|002 |BGN | 6 |USD | 3.75 |
|002 |BND | 9.5 |PHP | 8.5 |
|002 |BND |4.25 |USD |12.75 |
|002 |CAD |12.5 |USD | 6.75 |
|002 |INR | 35 |PHP |22.75 |
|002 |INR | 25 |USD |16.25 |
|002 |YEN |55.5 |PHP |16.55 |
|002 |YEN |77.5 |USD | 39.2 |
+-------+-----+--------------------+-----+--------------------+
但是我想要这样的结果:
+-------+-----+--------------------+-----+--------------------+
|CODE |CURR |FRONT-END CHARGE |CCY |BACK-END CHARGE |
+-------+-----+--------------------+-----+--------------------+
|002 |AUD |7 |PHP | 3.75 |
|002 | | |USD | 1.25 |
|002 |BGN |20 |PHP | 8.75 |
|002 | | |USD | 3.75 |
|002 |BND |13.75 |PHP | 8.5 |
|002 | | |USD |12.75 |
|002 |CAD |12.5 |USD | 6.75 |
|002 |INR |60 |PHP |22.75 |
|002 | | |USD |16.25 |
|002 |YEN |133 |PHP |16.55 |
|002 | | |USD | 39.2 |
+-------+-----+--------------------+-----+--------------------+
请注意,前端费用是每种货币每种费用的总和。
我尝试使用合并,但选择时它返回相同的表。我也尝试过自助加入,但每次收费的总和都不同。这是在Oracle 11g中
答案 0 :(得分:0)
这种类型的转换通常应该在表示层中完成-因为结果并不是真正的SQL表:行缺少列值。
但是,您可以使用窗口功能来做到这一点:
select code,
(case when row_number() over (partition by code, curr order by front_end_charge desc) = 1
then code
end) as code,
(case when row_number() over (partition by code, curr order by front_end_charge desc) = 1
then sum(front_end_charge) over (partition by code, curr)
end) as front_end_charge,
ccy, back_end_charge
from t
order by t.code, t.curr, t.front_end_charge desc;
重要的是,外部order by
与order by
表达式中的row_number()
相匹配。当出现order by
时,SQL查询仅以确定的顺序返回结果。