2016-10-07 13 views
0

を使用して分割:T-SQL:私は、次の表を持っているcase文

| RoomID | OrderID | Occupancy | Status  | 
+--------+---------+-----------+---------------+ 
| 01  | 101  | Vacant | inspection | 
| 01  | 102  | Occupied | Preservation | 
| 01  | 103  | Occupied | inspection | 
| 01  | 104  | Vacant | inspection | 
| 02  | 201  | Vacant | inspection | 
| 02  | 202  | Occupied | inspection | 
| 02  | 203  | Vacant | inspection | 
| 03  | 301  | Vacant | inspection | 
| 03  | 302  | Occupied | inspection | 
| 03  | 303  | Occupied | Preservation | 
| 03  | 304  | Occupied | Preservation | 
| 04  | 401  | Occupied | inspection | 
| 04  | 402  | Occupied | inspection | 
| 04  | 403  | Vacant | Preservation | 
| 04  | 404  | Occupied | inspection | 

私はOccupancyは=「占領」と任意の中Status =「保存」RoomIDレベルで自分のデータを取得する必要があります指定されたRoomIDのインスタンスです。

結果は次のようになります。

| RoomID | Flag | 
+--------+---------+ 
| 01  | 1  | 
| 02  | 0  | 
| 03  | 1  | 
| 04  | 0  | 

私は、これは簡単であるという印象を持っているが、私は現時点ではそれを見ることができない、あなたの助けに前もって感謝します!

答えて

1

条件付き集計を使用できます。

select roomid, 
count(distinct case when Occupancy = 'Occupied' and Status = 'Preservation' then 1 end) flag 
from tablename 
group by roomid 
1

UNIONを使用して以下のクエリを使用することもできます。

;with cte_1 
AS 
(SELECT DISTINCT RoomId 
    FROM YourTable 
    WHERE Occupancy='Occupied' AND Status='Predervation') 
    SELECT RoomId,1 Status 
    FROM cte_1 
    UNON 
    SELECT DISTINCT RoomId,0 Status 
    FROM YourTable t 
    WHERE NOT EXISTS(SELECT 1 FROM cte_1 c 
       WHERE t.RoomId=c.RoomId) 
関連する問題