将列标题转换为行数据 - sql

时间:2012-09-11 08:44:18

标签: sql sql-server

我的SQL查询打印结果如

North   South   West    East    Central
0       280     0       41      36

但我希望它像

North    0
South    280
West     0
East     41
Central  36

SQL: -

Select  Count(Case When Region=1 Then 1 Else Null End)[North],
    Count(Case When Region=2 Then 1 Else Null End)[South],
    Count(Case When Region=3 Then 1 Else Null End)[West],
    Count(Case When Region=4 Then 1 Else Null End)[East],
    Count(Case When Region=5 Then 1 Else Null End)[Central] 
    From ATM Where ATMStatus=0 And Bank=1

2 个答案:

答案 0 :(得分:3)

USE集团

SELECT 
   CASE Region 
    WHEN 1 THEN 'North'
    WHEN 2 THEN 'South' 
    WHEN 3 THEN 'West'
    WHEN 4 THEN 'East'
    WHEN 5 THEN 'Central' END AS Region  
    , COUNT(ID)   --or your primary key if it is different
FROM ATM
WHERE ATMStatus = 0 AND Bank = 1
GROUP BY Region

答案 1 :(得分:1)

 select case Region
     when 1 then 'North'
     when 2 then 'South'
     etc

 end, count(*)
 From ATM Where ATMStatus=0 And Bank=1  
 group by Region

你有区域表吗?这会使它变得更简单,特别是如果0行很重要的话。