如何在Oracle PL SQL中将列名显示为行

时间:2017-12-29 11:11:21

标签: sql oracle unpivot

我有一个查询来获取某些列的计数。 我得到输出没有错误,但我需要以不同的方式。 有人可以帮我在Oracle Pl / SQL中获得以下输出吗?

SELECT   
SUM (DECODE(COLUMN1,'Y',1,0)) AS COUNT1,  
SUM (DECODE(COLUMN2,'Y',1,0)) AS COUNT2,  
SUM (DECODE(COLUMN3,'Y',1,0)) AS COUNT3,  
SUM (DECODE(COLUMN4,'Y',1,0)) AS COUNT4,  
SUM (DECODE(COLUMN5,'Y',1,0)) AS COUNT5,  
SUM (DECODE(COLUMN6,'Y',1,0)) AS COUNT6   
FROM TABLE_NAME  
WHERE COLUMN7 IN ('X','Y');

 **OUTPUT:**  
-----------------------------------------
COUNT1|COUNT2|COUNT3|COUNT4|COUNT5|COUNT6
-----------------------------------------
5500  | 1245 | 5245 | 5675 | 7845 | 5324
-----------------------------------------

**Required Output**

COUNT1 | 5500  
-------------
COUNT1 | 1245 
-------------
COUNT1 | 5245 
-------------
COUNT1 | 5675 
-------------
COUNT1 | 7845 
-------------
COUNT1 | 5324
-------------

1 个答案:

答案 0 :(得分:2)

使用UNION

SELECT 'Count1' AS "Count", SUM (DECODE(COLUMN1,'Y',1,0)) AS Total 
FROM TABLE_NAME WHERE COLUMN7 IN ('X','Y')
UNION ALL
SELECT 'Count2' AS "Count", SUM (DECODE(COLUMN2,'Y',1,0)) AS Total 
FROM TABLE_NAME WHERE COLUMN7 IN ('X','Y')
UNION ALL
SELECT 'Count3' AS "Count", SUM (DECODE(COLUMN3,'Y',1,0)) AS Total 
FROM TABLE_NAME WHERE COLUMN7 IN ('X','Y')
UNION ALL
...

但是,如果您有一个group by列,则可以按其分组并在一个查询中使用该值。

<强>更新

您也可以使用UNPIVOT

执行此操作
SELECT *
FROM
(
  SELECT   
  SUM (DECODE(COLUMN1,'Y',1,0)) AS COUNT1,  
  SUM (DECODE(COLUMN2,'Y',1,0)) AS COUNT2,  
  SUM (DECODE(COLUMN3,'Y',1,0)) AS COUNT3,  
  SUM (DECODE(COLUMN4,'Y',1,0)) AS COUNT4,  
  SUM (DECODE(COLUMN5,'Y',1,0)) AS COUNT5,  
  SUM (DECODE(COLUMN6,'Y',1,0)) AS COUNT6   
  FROM TABLE_NAME  
  WHERE COLUMN7 IN ('X','Y')
)
UNPIVOT
(
  Total
  FOR COL IN(COUNT1,COUNT2,COUNT3,COUNT4,COUNT5,COUNT6)
)

SQL Fiddle Demo