如何计算SQL Server中具有特定值的行?

时间:2017-03-01 06:22:03

标签: sql-server

我喜欢下面格式化的表行。我需要根据状态计算行数。

E.g:

+----+-----------+----------------+
|SNo | Operation | Status         |
+----+-----------+----------------+
|1   |   OP10    | Complete       |
|1   |   OP10    | Complete       |
|2   |   OP10    | Complete       |
|2   |   OP10    | Complete       |
|2   |   OP10    | Complete       |
|3   |   OP20    | InProgress     |
|3   |   OP20    | InProgress     |
|3   |   OP20    | InProgress     |
|4   |   OP30    | Ready          |
|4   |   OP30    | Ready          |
+----+-----------+----------------+

输出:

Sno  Operation   CountStatus
----------------------------
1     OP10            2
2     OP10            3
3     OP20            3
4     OP30            0

如果状态为“完成”,我需要计算。 &安培; ' INPROGRESS&#39 ;.如果状态为“准备就绪”。意味着需要显示计数是' 0'。

4 个答案:

答案 0 :(得分:5)

使用条件聚合:

创建并填充样本表(在将来的问题中保存此步骤)

Declare @T as table
(
    Sno int,
    Operation char(4),
    Status varchar(10)
)

INSERT INTO @T VALUES
(1, 'OP10', 'Complete'),
(1, 'OP10', 'Complete'),
(2, 'OP10', 'Complete'),
(2, 'OP10', 'Complete'),
(2, 'OP10', 'Complete'),
(3, 'OP20', 'InProgress'),
(3, 'OP20', 'InProgress'),
(3, 'OP20', 'InProgress'),
(4, 'OP30', 'Ready'),
(4, 'OP30', 'Ready')

查询:

SELECT Sno, 
       Operation, 
       SUM(CASE WHEN Status IN('Complete', 'Inprogress') THEN 1 ELSE 0 END) As CountStatus
FROM @T
GROUP BY Sno, Operation
ORDER BY Sno

结果:

Sno Operation   CountStatus
1   OP10        2
2   OP10        3
3   OP20        3
4   OP30        0

答案 1 :(得分:0)

性能明智这会更好

Select t.sno,t.operation, tt.cno
from (select distinct t.sno, t.operation from tablename t) t 
inner join (select t.sno, 
cno = count(case when Status in ('Complete', 'InProgress') then 1 else null end)  
                    from tablename group by sno)tt on t.sno = tt.sno

答案 2 :(得分:0)

我使用了简单的案例陈述

SELECT
        SNO,Operation,SUM(CASE Status WHEN 'Complete' THEN 1 
                                  WHEN 'InProgress' THEN 1
                                  WHEN 'Ready' THEN 0 END) AS Cnt_Status
FROM Your_table
GROUP BY SNO,Operation

答案 3 :(得分:0)

尝试此查询

从table1中选择SNo,operation,COUNT(sno) 按sno,操作分组