Turn rows into columns in SELECT Oracle

Asked

Viewed 53 times

0

Below is a select for data query in a table:

SELECT
'OS:'||AT.CD_NUMERO_OS ||' ITEM:'|| AT.ITEM ||' ETAPA DA ATVD:'||AT.CD_ETAPA_ATIVID||' ATVD:'|| AT.CD_ATIVIDADE AS "DADOS DA OS",
AT.DT_INICIO AS "DATA DE INICIO",
AT.DT_TERMINO AS "DATA DE FIM"

FROM GMATIVID AT

INNER JOIN GMOSERVI OS ON OS.CD_NUMERO_OS = AT.CD_NUMERO_OS

WHERE OS.DT_OS BETWEEN TO_DATE(:data_abertura_os_inicial, 'DD/MM/YYYY') AND TO_DATE(:data_abertura_os_final, 'DD/MM/YYYY')
AND OS.SITUACAO LIKE 'E'

ORDER BY AT.CD_NUMERO_OS ASC, AT.ITEM ASC, AT.CD_ATIVIDADE ASC

Below follows the result of this consultation:

Resultado da consulta

I need to turn the lines into columns to fit the report we are developing, follows below as accurate information:

Consulta necessária

It is possible to perform this "transposition" of rows into columns directly in the SQL query?

  • 2

    Search Pir PIVOT or CASE PIVOT https://www.oracle.com/technical-resources/articles/database/sql-11g-pivot.html https://blogs.oracle.com/sql/how-to-convert-rows-to-columns-and-backagain-with-sql-aka-pivot-and-unpivot

1 answer

1

With PIVOT you solve this.

Example :

SELECT d.department_name, e.job_id, count(e.employee_id)
FROM hr.employees e
INNER JOIN hr.departments d
  ON d.department_id = e.department_id
GROUP BY d.department_name, e.job_id
ORDER BY d.department_name, e.job_id
;

WITH values_join
AS
(
  SELECT d.department_name department_name, e.job_id job_id, e.employee_id qty_empl
  FROM hr.employees e
  INNER JOIN hr.departments d
  ON d.department_id = e.department_id
)
SELECT * FROM values_join
  PIVOT
  (
  COUNT(qty_empl)
  FOR job_id IN ('AC_ACCOUNT','AC_MGR','AD_ASST','AD_VP','FI_ACCOUNT','FI_MGR','HR_REP',
                 'IT_PROG','MK_MAN','MK_REP','PR_REP','PU_MAN','SA_MAN','SA_REP',
                 'SH_CLERK','ST_CLERK','ST_MAN')
  )
ORDER BY department_name
;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.