我想查询SQL Server (Azure)中“间隙和孤岛”问题中最后一个孤岛的大小。
假设我有下表:
ID date status
500 2019-05-15 1
528 2019-05-16 0
538 2019-05-17 0
550 2019-05-18 1
580 2019-05-19 0
590 2019-05-20 0 ID是标识列date是date列状态是0或1。
我想知道状态被设置为0的天数。在这种情况下,今天是2019-05-20。
如何编写一个查询来拉取最后一个状态列的计数为0(即2)?
发布于 2019-05-31 02:57:58
您可以使用status = 1查找最近的记录,并使用status = 0对最近的行数进行计数。
select
count(*) as cnt
from yourTable
where [date] > (select max([date]) from yourTable where [status] = 1)发布于 2019-05-31 05:31:43
假设您想要计算行数(而不是使用日期算法),那么一个安全的方法是:
select count(*) as cnt
from t
where [date] > all (select [date] from t where status = 1);即使没有1,这也应该可以正常工作。
https://stackoverflow.com/questions/56384071
复制相似问题