Oracle:将两行值合并为具有新列名的一行

时间:2018-09-12 19:23:09

标签: sql oracle oracle11g

我使用的版本是Oracle数据库12c。

select id,currency_code,currency_classification_code,amount from table;

数据:

id   currency_code    currency_classification_code    Amount
1    USD              Reporting                       111111
1    AUD              BASE                            222222

预期结果:

id   Amt_in_base_curncy  base_curncy_code  Amt_in_rptng_curncy rptng_curncy_code
1    222222              AUD               111111              USD

我希望通过创建四个新列来使用上述格式的数据。

如果您需要更多详细信息,请告诉我。

请帮助。

4 个答案:

答案 0 :(得分:1)

您可以使用Builder::macro('with', function (...$tables) { $period = ???; // How do I set this for every call to "with()"? $joins = collect($this->joins)->pluck('table'); foreach ($tables as $table) { $tableName = $period.'_'.$table; if (!$joins->contains($tableName)) $this->leftJoin($tableName, $tableName.'.symbol', '=', 'profile.symbol'); } return $this; }); class List extends BaseList { // The current period protected $period; public function __construct($period) { $this->period = $period; } protected function base() { return DB::table('profile')->select('profile.symbol') ->with('technicals') // This is the macro that needs $this->period. ->limit(100); } } ,例如:

join

答案 1 :(得分:1)

一种方法是条件聚合:

select id, 
max(case when currency_classification_code = 'BASE' then Amount end) as Amt_in_base_curncy,
max(case when currency_classification_code = 'BASE' then currency_code end) as base_curncy_code,
max(case when currency_classification_code = 'Reporting' then Amount end) as Amt_in_rptng_curncy,
max(case when currency_classification_code = 'Reporting' then currency_code end) as rptng_curncy_code
from t
group by id

答案 2 :(得分:1)

让我们走另一条路线:

如果不能确定在所有情况下每个ID都有'BASE'行和'Reporting'行,则需要使用FULL JOIN将数据放在一起:

WITH cteBase AS (SELECT *
                   FROM YOUR_TABLE
                   WHERE CURRENCY_CLASSIFICATION_CODE = 'BASE'),
     cteReporting AS (SELECT *
                        FROM YOUR_TABLE
                        WHERE CURRENCY_CLASSIFICATION_CODE = 'Reporting')
SELECT COALESCE(b.ID, r.ID) AS ID,
       b.AMOUNT AS Amt_in_base_curncy,
       b.CURRENCY_CODE AS base_curncy_code,
       r.AMOUNT AS Amt_in_rptng_curncy,
       r.CURRENCY_CODE AS rptng_curncy_code
  FROM cteBase b
  FULL OUTER JOIN cteReporting r
    ON r.ID = b.ID

答案 3 :(得分:1)

正是针对此类问题,Oracle具有PIVOT查询:

select *
  from (select id,currency_code,currency_classification_code,amount from table)
  pivot (sum(amount) as amt_in
        ,max(currency_code) as code 
     for (currency_classification_code) in ('BASE' as base_curncy, 'Reporting' as rptng_curncy))