SQL Server需要修改过程

时间:2013-06-11 13:39:02

标签: sql sql-server

我有一个存储过程,它产生如下输出:

Success  Fail  Progress
----------------------------
   1      2       3

但我希望输出为:

Recieved  Count
----------------
success     1
----------------
fail        2
----------------
progress    3

请有人帮我从我的sql server获取此输出。

当前的SQL:

select 
    sum(case when status='AK' then 1 else 0 end) as 'SUCCESS', 
    sum(case when status='E' then 1 else 0 end) as 'FAILURE', 
    sum(case when status NOT IN('AK','E')then 1 else 0 end) as 'PENDING' 
from t 
where [rec_datetime] BETWEEN '2008-02-11' AND DATEADD(DAY,1,'2008-02-11') 

3 个答案:

答案 0 :(得分:1)

您可以使用UNPIVOT将列移至行:

SELECT b.[Received], b.[Count]
FROM (SELECT[Success] = 1, [Fail] = 2, [Progress] = 3) a
UNPIVOT ([Count] FOR [Received] IN ([Success], [Fail], [Progress])) b

<强>输出

Received    Count
----------- -----------
Success     1
Fail        2
Progress    3

答案 1 :(得分:0)

替换你的select语句
select 'Success' as Received, sum(case when status='AK' then 1 else 0 end)  as [count]
 from t where [rec_datetime] BETWEEN '2008-02-11' AND DATEADD(DAY,1,'2008-02-11')
union all
select 'Fail', sum(case when status='E' then 1 else 0 end) 
 from t where [rec_datetime] BETWEEN '2008-02-11' AND DATEADD(DAY,1,'2008-02-11')
union all
select 'Progress' , sum(case when status NOT IN('AK','E')then 1 else 0 end)
 from t where [rec_datetime] BETWEEN '2008-02-11' AND DATEADD(DAY,1,'2008-02-11')

答案 2 :(得分:-1)

在没有看到您的代码或数据的情况下很难,但这样的事情可能有用:

select 'success' As Recieved, Success As [Count] from mytable
union all
select 'fail', Fail  from mytable
union all
select 'progress',  Progress from mytable