各組

2017-08-30 47 views
-1

樣品表中選擇各組

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  
+2

哪個域ID,隨機一個?你有什麼嘗試? –

+1

'WHERE domainid = 1'? –

+2

您的示例具有所有具有相同BatchID的行,並且輸出具有兩行。這不符合你對此事的解釋嗎? –

回答

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 
0

這似乎很容易,除非你想要別的東西 -

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

這裏是這樣做沒有一個子查詢的一個取巧的辦法:

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