T-SQL:使用case语句进行分区

时间:2016-10-07 16:50:58

标签: sql tsql partitioning flags

我有下表:

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

我需要在RoomID ='占用的Occupancy级别上提取数据。和Status ='保存'在任何给定RoomID的实例中。

结果应如下所示:

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

我的印象是这很简单,但我现在看不到它,请提前感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

您可以使用条件聚合。

i > 0

答案 1 :(得分:1)

您也可以使用UNION。

使用以下查询
{{1}}