I have a requirement to populate some data with some grouping.
DDL Script:
CREATE TABLE #TEMP
(
OTHERCOL VARCHAR(10),
RANK_NO INT,
TAG INT
)
INSERT INTO #TEMP VALUES ('OC1',1,0)
INSERT INTO #TEMP VALUES ('OC1',2,0)
INSERT INTO #TEMP VALUES ('OC1',3,0)
INSERT INTO #TEMP VALUES ('OC2',1,0)
INSERT INTO #TEMP VALUES ('OC2',2,0)
INSERT INTO #TEMP VALUES ('OC2',3,9999)
INSERT INTO #TEMP VALUES ('OC2',4,0)
INSERT INTO #TEMP VALUES ('OC2',5,0)
INSERT INTO #TEMP VALUES ('OC3',1,0)
INSERT INTO #TEMP VALUES ('OC3',2,0)
INSERT INTO #TEMP VALUES ('OC3',3,0)
Using DENSE_RANK
over OTHERCOL
, I have got FINAL_TAG
as shown here:
OTHERCOL | RANK_NO | TAG | FINAL_TAG |
---|---|---|---|
OC1 | 1 | 0 | 1 |
OC1 | 2 | 0 | 1 |
OC1 | 3 | 0 | 1 |
OC2 | 1 | 0 | 2 |
OC2 | 2 | 0 | 2 |
OC2 | 3 | 9999 | 2 |
OC2 | 4 | 0 | 2 |
OC2 | 5 | 0 | 2 |
OC3 | 1 | 0 | 3 |
OC3 | 2 | 0 | 3 |
OC3 | 3 | 0 | 3 |
However, I want the result to be as shown below in the desired value. I could achieve this in Excel, but I'm unable to so in SQL Server.
Details of the activity done is attached here
I have tried to use SELECT CASE
but it is not working as the value is getting reset... Is there any way to so that we can update the values of variable and use the same based on the condition?
2条答案
按热度按时间o2rvlv0m1#
You can get the desired value by applying a conditional running total using analytic function
sum()
andcase
clause :Demo here
osh3o9ms2#
You can do first a conditional count of
Tag
, excluding (by nulling out) the cases whereTag = 0
.Then do
DENSE_RANK
using that column as another ordering column.db<>fiddle