我有一个查询,根据事件是否在给定日期发生,返回1或0。这是按日期排序的。基本上,一个简单的结果集是:
Date | Type
---------------------
2010-09-27 1
2010-10-11 1
2010-11-29 0
2010-12-06 0
2010-12-13 1
2010-12-15 0
2010-12-17 0
2011-01-03 1
2011-01-04 0
我现在希望能够做的是计算单独的,非并发的'0'实例的数量 - 即计算有多少不同的0组出现。
在上面的例子中,答案应该是3(1组2,然后另一组2,最后1结束)。
希望上面的例子说明了我想要达到的目标。我一直在寻找,但我发现很难简洁地描述我在寻找什么,因此没有找到任何相关的东西。
提前致谢,
约什
答案 0 :(得分:3)
您可以在CTE中为每一行提供一个数字。然后,您可以将表连接到自身以查找上一行。知道前一行,您可以将前一行的数量加1,当前行为0.例如:
; with NumberedRows as
(
select row_number() over (order by date) as rn
, type
from YourTable
)
select sum(case when cur.type = 0 and IsNull(prev.type,1) = 1 then 1 end)
from NumberedRows cur
left join
NumberedRows prev
on cur.rn = prev.rn + 1
答案 1 :(得分:2)
这是“岛屿”问题的变体。我的第一个答案使用Itzik Ben Gan的双row_number
技巧来有效地识别连续的数据组。 Type,Grp
的组合标识数据中的每个岛屿。
You can read more about the different approaches to tackling this problem here.
;WITH T AS (
SELECT *,
ROW_NUMBER() OVER(ORDER BY Date) -
ROW_NUMBER() OVER(PARTITION BY Type ORDER BY Date) AS Grp
FROM YourTable
)
SELECT COUNT(DISTINCT Grp)
FROM T
WHERE Type=0
我的第二个答案需要单次传递数据。它不能保证工作,但其原理与许多人成功用于连接字符串而没有问题的技术相同。
DECLARE @Count int = 0
SELECT @Count = CASE WHEN Type = 0 AND @Count <=0 THEN -@Count+1
WHEN Type = 1 AND @Count > 0 THEN - @Count
ELSE @Count END
FROM YourTable
ORDER BY Date
SELECT ABS(@Count)
答案 2 :(得分:1)
使用Sql Server 2005 +
查看此示例DECLARE @Table TABLE(
Date DATETIME,
Type INT
)
INSERT INTO @Table SELECT '2010-09-27',1
INSERT INTO @Table SELECT '2010-10-11',1
INSERT INTO @Table SELECT '2010-11-29',0
INSERT INTO @Table SELECT '2010-12-06',0
INSERT INTO @Table SELECT '2010-12-13',1
INSERT INTO @Table SELECT '2010-12-15',0
INSERT INTO @Table SELECT '2010-12-17',0
INSERT INTO @Table SELECT '2011-01-03',1
INSERT INTO @Table SELECT '2011-01-04',0
;WITH Vals AS (
SELECT *,
ROW_NUMBER() OVER(ORDER BY Date) ROWID
FROM @Table
)
SELECT v.*
FROM Vals v LEFT JOIN
Vals vNext ON v.ROWID + 1 = vNext.ROWID
WHERE v.Type = 0
AND (vNext.Type = 1 OR vNext.Type IS NULL)