SQLl查询将行转换为列并为每个记录获取单行

时间:2017-07-02 04:10:42

标签: sql sql-server

我使用此查询将行转换为列

select 
    LAST_MOD_BY,
    (select count(*) 
     from tblALRT 
     where LAST_MOD_BY = 'USER2') 'Total Cases Worked',
    (case when STATUS_TYPE = 'Pending' then count(*) end) 'Pending' ,
    (case when STATUS_TYPE = 'Reassign' then count(*) end) 'Reassign'',
    (case when STATUS_TYPE = 'Lost' then count(*) end) 'Lost'
from 
    tblALRT 
where 
    LAST_MOD_BY = 'USER2' 
group by  
    STATUS_TYPE, LAST_MOD_BY

结果是:

query result

我想要以下结果

required result

请帮忙。

由于

2 个答案:

答案 0 :(得分:1)

我认为只需重新调整GROUP BY子句的顺序就可以修复代码,使其按预期工作:

select LAST_MOD_BY,(select count(*) from tblALRT where 
LAST_MOD_BY='USER2'
)'Total Cases Worked',
  (case when STATUS_TYPE = 'Pending' then count(*) end) 'Pending' ,
  (case when STATUS_TYPE = 'Reassign' then count(*) end) 'Reassign',
  (case when STATUS_TYPE = 'Lost' then count(*) end) 'Lost'
  from tblALRT 
where LAST_MOD_BY='USER2' 
group by LAST_MOD_BY, STATUS_TYPE;

这是因为LAST_MOD_BY(用户)列实际上就是您要分组的内容。我没有测试过这个,所以如果仍然不能在下面评论,我会自己测试一下。

希望它有所帮助!

答案 1 :(得分:0)

除了使用案例,您还可以使用子查询,例如:

SELECT LAST_MOD_BY,
    COUNT(*) AS ‘Total Cases Worked’,
    (SELECT COUNT(*) FROM tblALRT WHERE LAST_MOD_BY = ‘USER2’ AND STATUS_TYPE = ‘Pending’) AS ‘Pending’,
    (SELECT COUNT(*) FROM tblALRT WHERE LAST_MOD_BY = ‘USER2’ AND STATUS_TYPE = ‘Reassign’) AS ‘Reassign’,
    (SELECT COUNT(*) FROM tblALRT WHERE LAST_MOD_BY = ‘USER2’ AND STATUS_TYPE = ‘Lost’) AS ‘Lost’,
FROM tblALRT
WHERE LAST_MOD_BY = ‘USER2’