TSQL:通过查询的条件组

时间:2016-05-20 01:31:04

标签: sql sql-server tsql group-by

我需要获取Room_IDs报告为空的所有Status,然后仅在以后占用。

这是我用作示例的简化表:

 **Room_Id  Status    Inspection_Date**
   1        vacant      5/15/2015
   2        occupied    5/21/2015
   2        vacant      1/19/2016
   1        occupied   12/16/2015
   4        vacant      3/25/2016
   3        vacant      8/27/2015
   1        vacant      4/17/2016
   3        vacant     12/12/2015
   3        occupied    3/22/2016
   4        vacant       2/2/2015
   4        vacant      3/24/2015

我的结果应如下所示:

 **Room_Id  Status  Inspection_Date**
    1       vacant      5/15/2015
    1       occupied   12/16/2015
    1       vacant      4/17/2016
    3       vacant      8/27/2015
    3       vacant     12/12/2015
    3       occupied    3/22/2016

3 个答案:

答案 0 :(得分:4)

以下是exists使用correlated subquery

的一个选项
select * from yourtable t
where exists (
  select 1
  from yourtable c
  where c.room_id = t.room_id 
  group by c.room_id
  having min(case when status = 'vacant' then inspection_date end) <
         max(case when status = 'occupied' then inspection_date end)
  )

答案 1 :(得分:0)

试试这个

;WITH cte 
     AS (SELECT *,
                Row_number()OVER(partition BY [room_id] ORDER BY [inspection_date])rn,                 FROM   YOurtable) 
SELECT room_id, 
       status, 
       [inspection_date] 
FROM   cte a 
WHERE  EXISTS (SELECT 1 
               FROM   cte b 
               WHERE  a.room_id = b.room_id 
                      AND b.rn = 1 
                      AND b.status = 'vacant') 
       AND EXISTS(SELECT 1 
                  FROM   cte c 
                  WHERE  a.room_id = c.room_id 
                         AND c.status = 'occupied') 

答案 2 :(得分:0)

SQLFiddle Demo

select * From table1 where room_id in(
SELECT room_id
FROM
  (SELECT lag(inspection_date,1,NULL) 
            over (partition BY room_id
                    ORDER BY status DESC) 
        AS prev_Inspection_date,
     t.*
      FROM
      (SELECT room_id,
             CASE WHEN status='vacant' THEN min(inspection_date) ELSE max(inspection_date) END 
       AS inspection_date,                                                                                               status
      FROM table1
      GROUP BY room_id,               status
       ) t
    ) s
WHERE prev_Inspection_date < inspection_date
  AND prev_Inspection_date IS NOT NULL)