SQL - 如果与前一行相比包含类似的信息,如何跳过一行?

时间:2015-10-29 15:21:14

标签: sql-server-2008

我的表看起来像这样:

ID#  Type    Color
1.   Clothes Red
2.   Clothes Orange
3.   Clothes OrangeYellow
4.   Clothes Green
5.   Clothes Red

期望的结果:

ID#  Type    Color
1.   Clothes Red
2.   Clothes Orange
4.   Clothes Green
5.   Clothes Red

我的SQL似乎不支持LAG功能

提前致谢。

1 个答案:

答案 0 :(得分:0)

您可以使用LIKE% previous-color %

一起使用此子查询方法
SELECT c.ID, c.Color
FROM dbo.Colors c
WHERE NOT EXISTS  -- check if previous row has a similar color
(
    SELECT 1 FROM dbo.Colors cPrev
    WHERE cPrev.ID = (SELECT MAX(cMax.ID) 
                      FROM dbo.Colors cMax
                      WHERE cMax.ID < c.ID)  -- maximum id lower than this
    AND c.Color LIKE '%' + cPrev.Color + '%'
)