用formate显示组中的数据

时间:2016-09-29 10:57:22

标签: sql join group-by

Name       Status
A           Fail
B           open 
c           fail
A           Success
A           open
A           Success

我想输出像,

Name   S_open   S_Success   S_All
A        1        2          4
B        1        0          1
C        0        0          1

2 个答案:

答案 0 :(得分:2)

试试这个

SELECT Name,
   SUM(CASE WHEN Status='open' THEN 1 END) AS S_open,
   SUM(CASE WHEN Status='Success' THEN 1 END) AS S_Success,
   SUM(1) AS S_All
FROM Table
GROUP BY Name;

答案 1 :(得分:0)

你也可以试试这个;

SELECT 
       upper(name),
       SUM(S_OPEN) S_open,
       SUM(S_SUCCESS) S_Success,
       count(*) S_All
FROM 
(
       select name, 
              CASE WHEN upper(status) = 'OPEN' THEN 1 ELSE 0 END S_OPEN,
              CASE WHEN upper(status) = 'SUCCESS' THEN 1 ELSE 0 END S_SUCCESS
       from TABLE
) t
GROUP BY upper(name) order by 1