我有一个存储数据的表:
ItemID Date Value
01 1/1/15 1
01 2/1/15 2
01 3/1/15 0
01 4/1/15 0
01 5/1/15 3
01 6/1/15 1
如何在SQL中生成一个报告,显示每个项目所有零周期的开始和结束日期?
在这个例子中,我会得到:
ItemID Start End
01 3/1/14 4/1/15
条件是一年中会有多个零时段,并且所有这些都应该出现在报告中(这样简单的组将不会出现)。
非常感谢!
答案 0 :(得分:1)
这将返回所有连续零START
的{{1}}和END
日期。
VALUE
示例数据
;WITH Cte AS(
SELECT *,
RN = DATEADD(MONTH,- ROW_NUMBER() OVER(PARTITION BY ItemID ORDER BY [Date]), [Date])
FROM Test
WHERE Value = 0
)
SELECT
ItemID,
Start = MIN([Date]),
[End] = MAX([Date])
FROM Cte
GROUP BY
ItemID, RN
<强> RESULT 强>
ItemID Date Value
------ ---------- -----------
01 2015-01-01 1
01 2015-02-01 2
01 2015-03-01 0
01 2015-04-01 0
01 2015-05-01 3
01 2015-06-01 1
01 2015-07-01 0
01 2015-08-01 0
01 2015-09-01 0
答案 1 :(得分:0)
更通用的解决方案(适用于2012 +):
with x as (
select *,
case when lag(value) over(partition by itemid order by date) <> value then 1 else 0 end as l
from #t
),
y as (
select *, sum(l) over(partition by itemid order by date) as grp
from x
where value = 0
)
select itemid, min(date), max(date)
from y
group by itemid, grp
order by itemid, grp