如何在SQL中将常量值更改为列标题?

时间:2017-05-09 13:15:07

标签: sql db2 db2-400

SQL查询:

select type,count(*), 'Active'                            
   from file where removed = '0'                                
union all 
select type,count(*), 'Removed' 
   from file where removed = '1'  

给出:

 TYPE                     COUNT ( * )   Constant value  
  A                         24,168      Active       
  A                              1      Removed      
  B                          8,280      Active       
  B                          1,263      Removed               

但是,如何更改SQL以获取:

TYPE                     Active  Removed   
A                         24,168    1       
B                          8,280  1,263  

补充的可选问题:包含以下总数的最佳方法是什么?

TYPE                     Active  Removed   
A                         24,168      1       
B                          8,280  1,263  
Total                     32,448  1,264    

这是我对补充内容的最佳答案,如果您发现任何缺陷或改进,请告知我们:

select 
    type, 
    sum(CASE WHEN removed = '0' THEN 1 ELSE 0 END) 'Active',
    sum(CASE WHEN removed = '1' THEN 1 ELSE 0 END) 'Removed'                            

from file                                
Group by type

union all

select 'Total',
sum(CASE WHEN removed = '0' THEN 1 ELSE 0 END) 'Active',
sum(CASE WHEN removed = '1' THEN 1 ELSE 0 END) 'Removed'                            

from file                                                         

感谢所有评论或回答的人,感谢您的帮助。

3 个答案:

答案 0 :(得分:5)

您可以尝试:

select 
    type, 
    sum(CASE WHEN removed = '0' THEN 1 ELSE 0 END) 'Active',
    sum(CASE WHEN removed = '1' THEN 1 ELSE 0 END) 'Removed'                            
from file                                
Group by type

答案 1 :(得分:2)

使用case表达式进行条件聚合:

select type,
       count(case when removed = '0' then 1 end) as "Active",                            
       count(case when removed = '1' then 1 end) as "Removed"                           
from file                       
group by type

如果有许多行的其他删除值超过0/1,并且该列已编入索引,则可以输入

WHERE removed IN ('0','1')

加快速度!

答案 2 :(得分:1)

为了在没有union的情况下获得总答案,请尝试:

select 
  coalesce(type, 'Totals') type,
  sum(CASE WHEN removed = '0' THEN 1 ELSE 0 END) Active,
  sum(CASE WHEN removed = '1' THEN 1 ELSE 0 END) Removed
from file                                
Group by rollup(type)

适用于v6.1及更高版本。