如何在这里使用group by查询

时间:2015-01-23 12:25:53

标签: c# sql-server-2005

Id  BatchName      TblName           SubBatchName     Status
1   12032014    Tbl_12032014_raw2_1  raw2           Complete    
2   12032014    Tbl_12032014_raw2_2  raw2           Complete    
3   12182014    Tbl_12182014_raw3_1  raw3           Complete        
4   12182014    Tbl_12182014_raw3_2  raw3           Complete        
5   12182014    Tbl_12182014_raw4_1  raw4           Complete        
6   12182014    Tbl_12182014_raw4_2  raw4           Complete        
7   12062014    Tbl_12062014_raw5_1  raw5           Complete    
8   12062014    Tbl_12062014_raw5_2  raw5           Complete
9   12062014    Tbl_12062014_raw5_3  raw5           InComplete  

我想要输出如下

BatchName                                                                                 
--------------------
12032014  
12182014                                            

如果所有batchname行的状态都已完成,那么只有BatchName获取选择

由于

2 个答案:

答案 0 :(得分:1)

按批次分组,仅处理除Complete

以外的其他状态的人
select batchname
from your_table
group by batchname
having sum(case when status <> 'Complete' or status is null
                then 1 
                else 0 
           end) = 0

答案 1 :(得分:1)

所以你希望所有BatchName所有状态都是Complete

您也可以使用Group By代替NOT EXISTS

SELECT DISTINCT t1.BatchName 
FROM dbo.TableName t1
WHERE t1.Status = 'Complete'
AND NOT EXISTS( SELECT 1 FROM dbo.TableName t2
                WHERE  t1.BatchName = t2.BatchName 
                 AND   ISNULL(t2.Status,'') <> 'Complete')

Demo