从行中删除重复项并保持顺序sql

时间:2014-03-21 12:29:21

标签: sql sql-server-2008 duplicates

我有一张表如下

SeriesVariables_ID     SeriesVariables_Label     SeriesVariables_Value    Series_ID
143                    Batch Number              Test20PassAll            28
144                    SerialNo                  SIMTEST                  28
145                    Seg Pull Date             20/1/2014                28
146                    Seg Pull Time             101010                   28
147                    Batch Number              Test20PassAll            28
148                    SerialNo                  SIMTEST                  28
149                    Seg Pull Date             20/1/2014                28
150                    Seg Pull Time             101010                   28
151                    Batch Number              Test20PassAll            7
152                    SerialNo                  SIMTEST2                 7
153                    Seg Pull Date             20/2/2014                7
154                    Seg Pull Time             202020                   7

我想要的是保持表的顺序并删除重复项。结果看起来像这样

SeriesVariables_ID     SeriesVariables_Label     SeriesVariables_Value    Series_ID
143                    Batch Number              Test20PassAll            28
144                    SerialNo                  SIMTEST                  28
145                    Seg Pull Date             20/1/2014                28
146                    Seg Pull Time             101010                   28
151                    Batch Number              Test20PassAll            7
152                    SerialNo                  SIMTEST2                 7
153                    Seg Pull Date             20/2/2014                7
154                    Seg Pull Time             202020                   7

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

如果您正在运行SQL,我在https://stackoverflow.com/a/18949/1781207找到答案对这些情况非常有帮助。它还可以保留最低的SeriesVariables_ID。

例如,在您的代码中应该是(其中" MyTable"是您的表的名称)

DELETE MyTable 
FROM MyTable
LEFT OUTER JOIN (
   SELECT MIN(SeriesVariables_ID) as RowId, SeriesVariables_Label, SeriesVariables_Value, Series_ID
   FROM MyTable 
   GROUP BY SeriesVariables_Label, SeriesVariables_Value, Series_ID
) as KeepRows ON
   MyTable.SeriesVariables_ID = KeepRows.RowId
WHERE
   KeepRows.RowId IS NULL

您可以通过单独运行内部select语句来测试以查看所选行

SELECT MIN(SeriesVariables_ID) as RowId, SeriesVariables_Label, SeriesVariables_Value, Series_ID
FROM MyTable
GROUP BY SeriesVariables_Label, SeriesVariables_Value, Series_ID