2013-05-02 84 views
-1

我的表是這樣的.....TSQL,刪除基於行指數排


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

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

我只想要回...因爲我

Red Boys  1 
Red Girls  2 

那有兩個條目的紅色,我想跳過/刪除所有的行,如果他們的計數是隻有1.換句話說,我只對行的興趣,如果他們的計數超過「1」。

+1

是'Count'一個字段,或使用聚合函數計算次數? – 2013-05-02 22:34:50

+0

其驅動列使用row_number()函數 – highwingers 2013-05-02 22:36:53

+0

爲什麼人們會把它投下來。 – highwingers 2013-05-02 22:50:08

回答

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 | 
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 
+0

爲什麼'計數(*)'而不是'計數(AttName)',因爲它是唯一重要的計數... – phadaphunk 2013-05-02 22:40:05

+1

而他希望列'AttName','Title'和'Count_indes'的事實如何結果 ? – phadaphunk 2013-05-02 22:41:55

+1

@PhaDaPhunk不同之處在於您是否需要計算空值。根據反饋更新了查詢,謝謝。查看http://stackoverflow.com/questions/3003457/count-vs-countcolumn-name-which-is-more-correct – AaronLS 2013-05-02 22:54:01