Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
ie. To have another Column, which groups consecutive 1 as the value for flag and put a # starting from 0, incrementing by 1.No number for flag = 0.Thanks in advance Srinika
robvolk
Most Valuable Yak
15732 Posts
Posted - 2011-05-19 : 14:48:54
This works, but it's kludgey:
WITH a(col, flag, posn, dif) AS (SELECT CASE WHEN flag=1 THEN 1+posn-RANK() OVER (PARTITION BY flag ORDER BY posn) ELSE NULL END, * FROM myTable)SELECT CASE WHEN flag=1 THEN DENSE_RANK() OVER (ORDER BY col)-1 END col, flag, posn, dif FROM a ORDER BY posn