Turtleman10
Turtleman10

Reputation: 119

Update based on a select statement SQL Server 2005

I have a select statement that gives me the results I need for my update but I have no idea how to incorporate it into the update. Below is the select statement and the results.

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

My update looks like this

update inmast
set fabccode = 'A'

I'm guessing my select would some how go into the where clause but I'm not sure how.

Upvotes: 0

Views: 54

Answers (3)

Jon
Jon

Reputation: 122

I like using CTEs as they tend to be more maintainable, they're (in my opinion) far more readable, and they seem to perform as well as nested SQL statements and oftentimes perform better (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'

Upvotes: 0

MikkaRin
MikkaRin

Reputation: 3084

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)

Upvotes: 0

Dave C
Dave C

Reputation: 7392

Updating top 20 percent is tricky... because you can't put an order by in an update.

I would do something like this:

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)

Run this is a select and make sure it works for you as expected. If yes, then you can just remove the select line, and uncomment the update line.

Alternate solution:

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

Upvotes: 1

Related Questions