2016-10-04 36 views
0

我不知道如何解释我的问题,所以我显示了示例数据。删除同一列中的数据

我有以下表

--------------------------------- 
|RecID |TypeOfData |Data  | 
|21 |Label  |Name  | 
|21 |Data  |Sam  | 
|22 |Label  |Name  | 
|23 |Label  |Name  | 
|23 |Data  |Nimble  | 

我想删除所有不具备下面这些数据的那些标签记录。 所以在上面的例子中需要删除RecID = 22。

请帮助我。

DB是SQL Server 2008.

+0

@Shiva参见RecID 21和RecID 22.建议ID dosent具有低于标签数据。 –

回答

1

可能是可以使用子查询,其中·REC_ID的计数= 1

delete from my_table 
    where Rec_id in (select RecID from my_table 
        group by RecId 
        having count(*) =1) 
and TypeOdData = 'Label' 
1

这是你想要的吗?

delete t 
    from t 
    where t.typeofdata = 'Label' and 
      not exists (select 1 
         from t t2 
         where t2.recid = t.recid and t2.typeofdata = 'Data' 
        ); 

“以下”不意味着关系表中任何东西,因为表表示无序集。

+0

非常感谢。它像魅力一样工作。 –

+0

@NimbleFungus。 。 。有没有理由不接受这个答案?你可以选择你喜欢的答案,但我很好奇。 –

+0

我选择其他,因为我不愿意不使用不存在。那是唯一的原因。谢谢...!!我想把这两个都标记为答案。 –

0
WITH CTE(TypeOfData, Data, Rn) 
AS 
(
SELECT [TypeOfData], [Data], 
    RN = ROW_NUMBER() OVER(PARTITION BY TypeOfData, DATA ORDER BY TypeOfData,Data) 
FROM tbl 
WHERE TypeOfData ='label' 
) 
DELETE FROM CTE WHERE RN > 1