条件分组查询

时间:2016-06-16 23:36:40

标签: sql sql-server tsql group-by

我需要获取Room_IDs所有Status所有Inspection_Date在最后一个 **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 2 occupied 5/21/2015 2 vacant 1/19/2016 3 vacant 8/27/2015 3 vacant 12/12/2015 3 occupied 3/22/2016 之间的差异。

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

Select *
FROM TableX x1
WHERE EXISTS 
( SELECT 1 
FROM TableX X2
WHERE X2.Room_Id = X1.Room_Id
GROUP BY X2.Room_Id
HAVING  max (Status) <> min (Status))

我的结果应如下所示:

render()

我试过这个,但老实说我不确定逻辑是否正确。

BasicDetails

2 个答案:

答案 0 :(得分:1)

使用row_number函数获取每个room_id的第一个(最新的inspection_date)行,并将其连接到剩余的行(针对该房间),并检查这些行中的任何行的状态是否不同。如果不同,请选择room_id,然后选择表room_id中的所有行。

select * from tablename
where room_id in (
select t1.room_id 
from (select t.*, row_number() over(partition by room_id order by inspection_date desc) rn 
      from tablename t) t1
join tablename t2 on t1.room_id = t2.room_id and t1.rn = 1
where t1.status <> t2.status
)

Sample Demo

答案 1 :(得分:0)

但是最后和任何先前的相同是两个或更多的值

select t1.room_id 
from ( select t.*
            , row_number() over(partition by room_id, status order by inspection_date desc) rn
            , count(*)  over(partition by room_id, status order by inspection_date desc) cnt
     ) tt 
 where tt.rn = 1 
   and tt.cnt > 1