不同列下单行中的多行SQL

时间:2016-02-08 05:15:09

标签: sql oracle

请查看以下示例:

Empid.   Compcode.     Amount
101.        Basic.     1000
101.        Hra.       200
102.        Basic.     1200
102.        Hra.       200
102.        Medical.   100

我想格式化数据,如下所示:

Emplid     basic.  Hra.      Medical
101.       1000.   200.     
102.       1200.   200.      100

有没有办法使用Oracle SQL生成此输出?

2 个答案:

答案 0 :(得分:1)

您的问题将通过在SQL中使用PIVOT来解决。

SELECT *
FROM (
    SELECT 
       Empid,Compcode,Amount FROM TableName
) AS S
PIVOT
(
    SUM(Amount)
    FOR Compcode IN ('Basic', 'Hra', 'Medical')
)AS pvt

答案 1 :(得分:1)

    SELECT
    x.Emplid,
    MAX(DECODE(x.Compcode, 'Basic.', x.Amount)) AS Basic,
    MAX(DECODE(x.Compcode, 'Hra.', x.Amount)) AS Hra,
    MAX(DECODE(x.Compcode, 'Medical.', x.Amount)) AS Medical,  
    FROM
    (
      SELECT a.Emplid,
             a.Compcode,
             a.Amount
      FROM   your_table a
    )As x
GROUP BY x.Emplid;