How to get the transpose in sql (HANA)?

三世轮回 提交于 2019-12-12 03:40:01

问题


I have a query which returns the table which is like

 SELECT (CASE WHEN type=1 THEN 'A' 
                 WHEN type=2 THEN 'B' 

           END) as TYPE,COUNT(*) AS COUNT
            from TYPE_TABLE GROUP BY TYPE

(I use case to have the count in each types).

count     type
_____     _____
123         A
124         B
120         C

I want to have the table to be like this

 A       B       C
___     ___     ___
123      124     120

So actually I need the transpose of the column count.How do I get this in HANA?


回答1:


A pure SQL solution (SQL Server)

select 
  [A] 
  , [B]
  , [C]
from
(
  select Type,[Count]
  from ( SELECT (CASE WHEN type=1 THEN 'A' 
             WHEN type=2 THEN 'B' 
             .....   
       END) as TYPE,COUNT(*) AS COUNT
        from TYPE_TABLE GROUP BY TYPE) Table1
) x
pivot
(
  SUM(Count)
  for Type in([A], [B], [C])
)p

Demo




回答2:


Since there are only 3

you could just

SELECT SUM(CASE WHEN TYPE = 1 THEN 1 ELSE 0 END) AS A,
       SUM(CASE WHEN TYPE = 2 THEN 1 ELSE 0 END) AS B,
       SUM(CASE WHEN TYPE = 3 THEN 1 ELSE 0 END) AS C
FROM yourTable


来源:https://stackoverflow.com/questions/43131323/how-to-get-the-transpose-in-sql-hana

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!