我根据以下标准在列中需要删除或保留的值列表:
如果相同的ID具有以下类型(在相同的ID上):1000、1100、1200、1300和其他任何类型,例如700、800、900等。我需要删除这些类型( 1000、1100、1200、1300)
但是,如果ID仅具有以下类型:1000、1100、1200、1300并且没有其他类型,则保留它们
ID | TYPE
40208001 | 700
40208001 | 1100
40209017 | 900
40209017 | 800
40209017 | 910
40209017 | 1200
40210494 | 1100
40210494 | 1000
40210494 | 1200
40210551 | 400
40210551 | 1200
40210767 | 1200
40210767 | 800
40211724 | 1300
40211724 | 900
40211724 | 500
我想要的是
ID | TYPE
40208001 | 700
40208001 |
40209017 | 900
40209017 | 800
40209017 | 910
40209017 |
40210494 | 1100
40210494 | 1000
40210494 | 1200
40210551 | 400
40210551 |
40210767 |
40210767 | 800
40211724 |
40211724 | 900
40211724 | 500
答案 0 :(得分:1)
在WHERE子句中使用EXISTS条件查找此类行:
UPDATE t
SET TYPE = NULL
WHERE TYPE IN (1000, 1100, 1200, 1300)
AND EXISTS (
SELECT 1
FROM t AS x
WHERE ID = t.ID
AND TYPE NOT IN (1000, 1100, 1200, 1300)
)
如果要选择数据,则可以将上面的内容重写为“外部应用”:
SELECT ID, CASE
WHEN TYPE IN (1000, 1100, 1200, 1300) AND hasother = 'y' THEN NULL
ELSE TYPE
END AS TYPE
FROM t
OUTER APPLY (
SELECT TOP 1 'y'
FROM t AS x
WHERE ID = t.ID AND TYPE NOT IN (1000, 1100, 1200, 1300)
) OA(hasother)
答案 1 :(得分:1)
您可以使用以下查询获得结果。
select t1.ID, (case when length(t1.type) > min_l then NULL else t1.type end) type
from test t1
join
(select ID,length(Min(type)) min_l from test group by ID) t2
on t1.ID = t2.ID
答案 2 :(得分:0)
您还可以使用如下查询。 逻辑是找到一组值在数千范围内的id,然后将其与带有条件条件的原始表连接起来
; with idsWithTypeInThousands as
(
select id from sourcetbl where type in (1000, 1100, 1200, 1300)
group by id
)
select s.id, case when i.id is not null and type not in (1000, 1100, 1200, 1300) then null else type end
from sourcetbl s left join idsWithTypeInThousands i
on i.id=s.id
答案 3 :(得分:0)
尝试一下:
Declare @ListValues TABLE(Id int, [Type] int)
INSERT INTO @ListValues
SELECT 40208001,700 Union All
SELECT 40208001,1100 Union All
SELECT 40209017,900 Union All
SELECT 40209017,800 Union All
SELECT 40209017,910 Union All
SELECT 40209017,1200 Union All
SELECT 40210494,1100 Union All
SELECT 40210494,1000 Union All
SELECT 40210494,1200 Union All
SELECT 40210551,400 Union All
SELECT 40210551,1200 Union All
SELECT 40210767,1200 Union All
SELECT 40210767,800 Union All
SELECT 40211724,1300 Union All
SELECT 40211724,900 Union All
SELECT 40211724,500
;with cte
As
(
Select Id
,SUM(CASE WHEN Type<1000 THEN 1 ELSE 0 END)As Type1Count
,SUM(CASE WHEN Type<1000 THEN 0 ELSE 1 END) As Type2Count
from @ListValues
Group by Id
)
Update l
set Type=NULL
from cte c
JOIN @ListValues l on c.Id=l.Id
WHERE Type2Count>0 and Type1Count>0 and l.Type>1000
Select * from @ListValues order by id
注意:“类型”列上的条件可以根据您的要求进行更改。从您的问题描述中,我得出了条件(类型> 1000和类型<100)。