TSQL,根据Row-Index删除行

时间:2013-05-02 22:32:29

标签: sql-server tsql

我的表就像这样......


**AttName**     **Title**        **Count_Index**

Red                Boys              1
Red                Girls             2
Green              Boys              1
Blue               Boys              1

我只想回来......

Red  Boys        1
Red  Girls       2

多数民众赞成因为我有两个条目的Red,如果他们的Count只有1,我想跳过/删除所有ROW。换句话说,如果他们的计数超过“1”,我只对行感兴趣。< / p>

2 个答案:

答案 0 :(得分:2)

尝试

SELECT * 
  FROM table1
 WHERE AttName IN (SELECT AttName FROM table1 GROUP BY AttName HAVING COUNT(*) > 1)

<强> SQLFiddle

输出

| ATTNAME | TITLE | COUNT_INDEX |
---------------------------------
|     Red |  Boys |           1 |
|     Red | Girls |           2 |

答案 1 :(得分:0)

好的,这是经过测试的。我喜欢在查找重复项时使用窗口函数。特别是因为避免在where子句中进行子选择,并且从同一个表中进行两次。相反,所有需要的列都已在子选择中拉入。虽然窗口功能有时会很昂贵。

Select *, ROW_NUMBER() over (Partition by AttrName Order By AttrName) --probably better to order by whatever the primary key is for consistent results, esepcially if you plan to use this in a delete statement
From (
  SELECT AttName, title, COUNT(AttrName) over (partition by AttrName) as cnt
  FROM yourtable
) as counted
Where counted.cnt > 1