我有一个表,其中包含如下数据:
Name Code Sequence AutoIncrementId
------------------------------------------------
Prashant 14323 1 11
Prashant 14323 1 12
Prashant 14323 1 13
Prashant 14323 1 14
Nishant 11323 2 11
Nishant 11323 2 12
Nishant 11323 2 13
Nishant 11323 2 14
Sushant 13223 3 11
Sushant 13223 3 12
Sushant 13223 3 13
Sushant 13223 3 14
Jishant 14223 4 11
Jishant 14223 4 12
Jishant 14223 4 13
Jishant 14223 4 14
预期输出为:
Name Code Sequence AutoIncrementId
------------------------------------------------
Prashant 14323 1 11
Nishant 11323 2 12
Sushant 13223 3 13
Jishant 14223 4 14
示例查询以生成数据:
CREATE TABLE #temp
(
Name NVARCHAR(200),
Code NVARCHAR(200),
Sequence NVARCHAR(200),
AutoIncrementId NVARCHAR(200)
)
INSERT INTO #temp VALUES ('Prashant',14323,1,11)
INSERT INTO #temp VALUES ('Prashant',14323,1,12)
INSERT INTO #temp VALUES ('Prashant',14323,1,13)
INSERT INTO #temp VALUES ('Prashant',14323,1,14)
INSERT INTO #temp VALUES ('Nishant',11323,2,11)
INSERT INTO #temp VALUES ('Nishant',11323,2,12)
INSERT INTO #temp VALUES ('Nishant',11323,2,13)
INSERT INTO #temp VALUES ('Nishant',11323,2,14)
INSERT INTO #temp VALUES ('Sushant',13223,3,11)
INSERT INTO #temp VALUES ('Sushant',13223,3,12)
INSERT INTO #temp VALUES ('Sushant',13223,3,13)
INSERT INTO #temp VALUES ('Sushant',13223,3,14)
INSERT INTO #temp VALUES ('Jishant',14223,4,11)
INSERT INTO #temp VALUES ('Jishant',14223,4,12)
INSERT INTO #temp VALUES ('Jishant',14223,4,13)
INSERT INTO #temp VALUES ('Jishant',14223,4,14)
我尝试过的查询:
SELECT ROW_NUMBER() OVER(ORDER BY AutoIncrementId,Sequence) as RN,*
FROM #temp ORDER BY RN
答案 0 :(得分:3)
根据示例数据,您可以尝试使用distinct
SELECT distinct Namem,Code,Sequence,AutoIncrementId
FROM #temp
答案 1 :(得分:2)
我不确定您想要的逻辑是什么。这是一种返回所需结果的方法:
select Name, Code, Sequence,
min(AutoIncrementId) + Sequence - 1 as AutoIncrementId
from #temp
group by Name, Code, Sequence;
上面的假设看起来像数字的值是数字。但是我看到您已经将它们存储为字符串,所以:
select Name, Code, Sequence,
convert(int, min(AutoIncrementId)) + convert(int, Sequence) - 1 as AutoIncrementId
from #temp
group by Name, Code, Sequence
order by sequence;
Here是db <>小提琴。
答案 2 :(得分:1)
您必须使用子查询并在此处使用一些技巧
select Name,code,Sequence,AutoIncrementId from
(
SELECT *, dense_rank() OVER(partition by Name,code,Sequence ORDER BY AutoIncrementId) as RN
FROM #temp
) t where rn-Sequence=0
order by Sequence
Name code Sequence AutoIncrementId
Prashant 14323 1 11
Nishant 11323 2 12
Sushant 13223 3 13
Jishant 14223 4 14
答案 3 :(得分:1)