仅更新具有共享/类似值的行

时间:2014-07-15 22:15:04

标签: sql sql-server tsql

好的 - 我有一个简单的表 - 下面 - 我要做的是只识别那些具有共享值的行 - 所以任何具有共享“apc”值的行 - DO x else Do Y

CREATE TABLE #test (hcpcs varchar(10), apc varchar(100), rate money) 

INSERT INTO #test (hcpcs, apc)
SELECT '97110', '8009'
UNION ALL
SELECT '71020', '8009'
UNION ALL
SELECT '85025', '8006'

所以 - 从上面 - 所有那些共享“8009”的行 - 我将对这些行进行更新 - 它们将共享相同的“速率”。带有“8006”的行不会成为该更新的一部分

4 个答案:

答案 0 :(得分:1)

你想:

WHERE EXISTS (SELECT *
     FROM #test t2
     WHERE t2.apc = #test.apc
     AND t2.hcpcs != #test.hcpcs)

确保将apc编入索引,以便有效地完成此操作。

答案 1 :(得分:0)

您可以将CTE与Count(*) over ( Partition By apc)

一起使用
WITH CTE AS(
  SELECT t.hcpcs, t.apc, t.rate,
         count_apc = Count(*) over ( Partition By t.apc)
  FROM Test t
)
SELECT hcpcs, apc, rate
FROM cte 
WHERE count_apc > 1

Demo

您只需将Select替换为Update CTE,实际上您就会更新表Test

Demo

答案 2 :(得分:0)

您可以尝试如下,内部查询将获取已重复的apcgroup by apc将按行分组行,并获取多次出现的apc。

update #test
set rate = someval
where apc in ( 
select apc from #test
group by apc
having count(*) > 1
)

答案 3 :(得分:0)

select 
    distinct
    apc,
    countAPC = count(apc) over(partition by apc)
into
    #testShared
from 
    #test

update #test 
set 
    rate = 2
where
    apc = (select apc from #testShared where countAPC > 1)
相关问题