从每个组中选择

时间:2017-08-30 08:19:09

标签: sql sql-server

样本表

SELECT * FROM MachineMaster

MachineID | MachineName | BatchID  | StatusID | domainid
1         | Test1       | 50       | 500      | 1  
2         | Test2       | 50       | 500      | 2    
3         | Test3       | 50       | 500      | 1    
4         | Test4       | 50       | 500      | 2    
5         | Test5       | 50       | 500      | 3    

我希望每批中都有SELECT * WHERE statusid = 500SELECT one domain id。这是我想看到的......

  MachineID | MachineName | BatchID  | StatusID | domainid
    1       | Test1       | 50       | 500      | 1   
    3       | Test3       | 50       | 500      | 1    

3 个答案:

答案 0 :(得分:0)

除非你想要别的东西,否则看起来很容易 -

SELECT * 
FROM MachineMaster
WHERE StatusID = 500
AND domainid = 1

答案 1 :(得分:0)

您可以使用每个批次添加最小域ID的子查询,然后对其进行过滤:

select MachineID,MachineName,BatchID,StatusID,domainid
from   (
        select *,
               min(domainid) over (partition by BatchID) as mindomainid
        from   MachineMaster
        where  StatusID = 500
        ) base
where   domainid = mindomainid

答案 2 :(得分:0)

这是一种在没有子查询的情况下执行此操作的棘手方法:

SELECT TOP (1) WITH TIES t.*
FROM t
WHERE statusid = 500
ORDER BY ROW_NUMBER() OVER (PARTITION BY domainid ORDER BY domainid);