Oracle SQL仅将一列值作为输出中的单独列转置

时间:2019-01-24 07:40:24

标签: sql oracle oracle-sqldeveloper

我的SQL;

    SELECT
        created_date,
        response_status,
        count
    FROM
        t_bvs_txn_response_summary
    WHERE
        created_date > SYSDATE - 1 / 24
        AND   response_status IN (
            'successful',
            'Disconnection'
        )
    ORDER BY
        1;

具有以下输出;

Current Output

我想在单独的列中获取response_status列中的值,并针对特定实例针对每个值显示计数。

所需的输出将是这样的;

Desired Output

我是SQL新手,因此需要一些帮助。

3 个答案:

答案 0 :(得分:4)

您可以尝试使用条件聚合

    SELECT 
      created_date,
      sum(case when response_status='successful' then count end ) as 'successful',
      sum(case when response_status='Disconnection' then count end) as 'Disconnection'
      FROM t_bvs_txn_response_summary
      WHERE created_date > SYSDATE - 1 / 24 AND response_status IN ('successful', 'Disconnection')
      group by created_date

答案 1 :(得分:3)

尝试PIVOT

SELECT * FROM (
     SELECT
            created_date, 
            response_status,
            nvl(count,0) as count
        FROM
            t_bvs_txn_response_summary
        WHERE
            created_date > SYSDATE - 1 / 24
            AND   response_status IN (
                'successful',
                'Disconnection'
            )
)
PIVOT
(
  SUM(count)
  FOR response_status IN ('successful', 'Disconnection')
)
        ORDER BY
            1;

答案 2 :(得分:0)

仅当您要检索所有剩余的列和计数时,才使用此方法。计数将重复。

   SELECT
        created_date,
        response_status,
        count,count(*) over(partition by response_status)
    FROM
        t_bvs_txn_response_summary
    WHERE
        created_date > SYSDATE - 1 / 24
        AND   response_status IN (
            'successful',
            'Disconnection'
        )
    ORDER BY
        1;