防止基于序号位置删除SQL查询中的行

时间:2014-04-04 11:07:52

标签: sql sql-server

所以我有一组看起来像这样的行:

Text  Sequence
ITEM1  1
ITEM1  2
ITEM1  3
ITEM2  4
ITEM2  5
ITEM3  6
ITEM2  7
ITEM2  8
ITEM1  9
ITEM1  10

我希望结果如下:

Text  Sequence
ITEM1  1
ITEM2  4
ITEM3  6
ITEM2  7
ITEM1  9

所以我接受了第一行的实例,只保留了第一个序列号,但是如果项目在列表中进一步重复,我还会保留该实例的序列号。

我的SQL是:

SELECT Text,Seq=Min(Sequence)
FROM Items
GROUP BY Text
ORDER BY Seq

结果是:

Text  Sequence
ITEM1  1
ITEM2  4
ITEM3  6

GROUP BY Text语句正在删除第4行和第5行。我该如何避免?

3 个答案:

答案 0 :(得分:2)

调整后的脚本以允许序列中的空白

DECLARE @t TABLE(Text char(5), Sequence int)
INSERT @t VALUES
('ITEM1',1),('ITEM1',2),('ITEM1',3),('ITEM2',4),('ITEM2',5),
('ITEM3',6),('ITEM2',7),('ITEM2',8),('ITEM1',9),('ITEM1',10)

;WITH x as
(
  SELECT Text,Sequence,
    row_number() OVER (order by Sequence)
    - row_number() OVER (partition by text order by Sequence) grp
  FROM @t
)
SELECT text, MIN(Sequence) seq
FROM x
GROUP BY text, grp
ORDER BY seq

结果:

text  seq
ITEM1 1
ITEM2 4
ITEM3 6
ITEM2 7
ITEM1 9

答案 1 :(得分:0)

LAG可让您查看上一条记录。将文本与上一行进行比较。仅显示文本与上一行不同的行。

select sequence, text
from
(
  select sequence, text, lag(text) over (order by sequence) as prev_text
  from mytable
)
where prev_text != text
or prev_text is null -- for the first line
order by sequence;

答案 2 :(得分:0)

对此并不完全满意,因为我认为使用游标会有更优雅的解决方案:

DECLARE @text varchar(max)
DECLARE @sequence int
DECLARE @previousText varchar(max)=''
DECLARE @results TABLE (text varchar(max), sequence int)

DECLARE iterator CURSOR FOR 
SELECT Text, Sequence
FROM Items

OPEN iterator

FETCH NEXT FROM iterator
INTO @text, @sequence

WHILE @@FETCH_STATUS = 0

IF(@text<>@previousText)
BEGIN
    INSERT INTO @results (text,sequence) VALUES (@text,@sequence)
    SET @previousText=@text
    FETCH NEXT FROM iterator INTO @text, @sequence
END
ELSE
    FETCH NEXT FROM iterator INTO @text, @sequence

CLOSE iterator
DEALLOCATE iterator

SELECT * FROM @results