簡體   English   中英

Oracle 11g中的自聯接表

[英]Self Join Table in Oracle 11g

假設我有一個像這樣的查詢產生的表:

+-------+-----+--------------------+-----+--------------------+
|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               |
+-------+-----+--------------------+-----+--------------------+

請注意,前端費用是每種貨幣的每筆費用的總和。

我嘗試使用coalesce但它在選擇時返回相同的表。 我也嘗試過自我加入,但每項收費的總和都不同了。 這是在oracle 11g

這種類型的轉換通常應該在表示層中完成 - 因為結果實際上不是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匹配row_number()表達式中的order by order by存在時,SQL查詢僅以確定的順序返回結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM