基于select语句SQL Server 2005进行更新

时间:2014-06-19 13:47:36

标签: sql sql-server sql-server-2005

我有一个select语句,它为我提供了更新所需的结果,但我不知道如何将其合并到更新中。以下是select语句和结果。

select top 20 percent
fpartno
,(fytdiss * fmatlcost) as 'total'
from inmast
where fpartno not like 'CRV%'
and fcstscode = 'A'
group by fpartno, fytdiss,fmatlcost,fabccode
order by total desc

fpartno                         total
---------------------------------------------------
1062-20-0244                172821.4800000000
B50602                      91600.7205800000
BM6031PQ                    82978.3200000000
LY2F-DC12                   74740.9500000000
BM6033SQ                    51640.4200000000
DTM06-6S-E007               49810.4700000000

我的更新看起来像这样

update inmast
set fabccode = 'A'

我猜我的选择会如何进入where子句,但我不确定如何。

3 个答案:

答案 0 :(得分:1)

更新top 20 percent非常棘手...因为您无法在更新中添加order by

我会做这样的事情:

select *
-- update t set fabccode='a'
from inmast t
where fpartno in (
    select top 20 percent fpartno
    from inmast t
    where fpartno not like 'CRV%'
    and fcstscode = 'A'
    group by fpartno, fytdiss,fmatlcost,fabccode
    order by (fytdiss * fmatlcost) desc)

运行此项为select,并确保按预期方式为您服务。如果是,那么您可以删除select行,并取消注释update行。

替代解决方案:

select *
-- update t set fabccode='a'
from inmast t
join (select top 20 percent fpartno
      from inmast t
      where fpartno not like 'CRV%'
      and fcstscode = 'A'
      group by fpartno, fytdiss,fmatlcost,fabccode
      order by (fytdiss * fmatlcost) desc) x
on t.fpartno = x.fpartno

答案 1 :(得分:0)

update inmast
set fabccode = 'A'
where fpartno in (
select top 20 percent
fpartno
from inmast
where fpartno not like 'CRV%'
and fcstscode = 'A'
group by fpartno, fytdiss,fmatlcost,fabccode
order by (fytdiss * fmatlcost) desc)

答案 2 :(得分:0)

我喜欢使用CTE,因为它们往往更易于维护,它们(在我看来)更具可读性,并且它们的表现似乎与嵌套的SQL语句一样好,并且通常表现更好(ymmv)。

;WITH CTE_Updates AS
    (
    SELECT TOP 20 PERCENT
         fpartno
        ,(fytdiss * fmatlcost) AS 'total'
    FROM 
        inmast
    WHERE 
        fpartno NOT LIKE 'CRV%' AND 
        fcstscode = 'A'
    GROUP BY fpartno, fytdiss,fmatlcost,fabccode
    ORDER BY total DESC
    )
UPDATE CTE_Updates
SET fabccode = 'A'