Data Available in Table1
ID Name1 Address
1 nm1 abc
1 nm2 def
1 nm3 ghi
0 nm4 jkl
0 nm5 mno
0 nm6 pqr
1 nm7 stu
1 nm8 vwx
1 nm9 yza
0 nm10 bcd
Expected Output from Table1
ID Name1 Address Counter
1 nm1 abc 1
1 nm2 def 1
1 nm3 ghi 1
0 nm4 jkl 2
0 nm5 mno 2
0 nm6 pqr 2
1 nm7 stu 3
1 nm8 vwx 3
1 nm9 yza 3
0 nm10 bcd 4
Order must be sort using the key fields and need to generate the auto increment no in the expected output.
Thanks in advance.
You need to know how the rows are order. I suppose this is sample data and in your real scenario you can ordered the data in unique way. With your sample data I am using the following statement to order the rows:
CAST(REPLACE([Name], 'nm', '') AS INT)
There are different solutions of this (some depending on your SQL version, too). If you are using SQL Server 2012+
you can use the LAG
function to find if ID
value is changed from the previous and current row and then to sum this changes using OVER
clause:
DECLARE @DataSource TABLE
(
[ID] INT
,[Name] VARCHAR(12)
,[Address] VARCHAR(12)
);
INSERT INTO @DataSource ([ID], [Name], [Address])
VALUES (1, 'nm1', 'abc')
,(1, 'nm2', 'def')
,(1, 'nm3', 'ghi')
,(0, 'nm4', 'jkl')
,(0, 'nm5', 'mno')
,(0, 'nm6', 'pqr')
,(1, 'nm7', 'stu')
,(1, 'nm8', 'vwx')
,(1, 'nm9', 'yza')
,(0, 'nm10', 'bcd');
SELECT *
,SUM([change_made]) OVER (ORDER BY CAST(REPLACE([Name], 'nm', '') AS INT))
FROM
(
SELECT *
,IIF([ID] <> LAG([ID], 1, -1) OVER (ORDER BY CAST(REPLACE([Name], 'nm', '') AS INT)), 1, 0) AS [change_made]
FROM @DataSource
) DS
ORDER BY CAST(REPLACE([Name], 'nm', '') AS INT);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.