Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 362
  • Last Modified:

SQL Compare Two Rows Same ID and Update?

I'm at-a-loss trying to compare two table rows with the same ID.
I need to update the 'IsPriceChg' in the row where Price column data is greater.

I tried using  Select 'Top 1' ...

ID      [Date]                                           IsPriceChg      Harmonica
88      2012-07-29 00:00:00.000      NULL                1.00
88      2012-07-30 00:00:00.000      NULL                2.00

I have this much, but not working yet:


Update Toys
Set IsPriceChg = 1
where ListID = 88
and max([Harmonica]) > min([Harmonica])
0
WorknHardr
Asked:
WorknHardr
2 Solutions
 
Scott PletcherSenior DBACommented:
Update t
Set IsPriceChg = 1
FROM Toys t
INNER JOIN (
    SELECT ListID, MAX([Harmonica]) AS Max_Harmonica
    FROM Toys
    GROUP BY ListID
    HAVING MAX([Harmonica]) > MIN([Harmonica])
) AS t_max ON
    t_max.ListID = t.ListID AND
    t.Harmonica = t_max.Harmonica
0
 
Surendra NathCommented:
if you are using SQL 2005 or above you can use the below query

;with CTE  AS
(
 select row_number() OVER(partition by ID,ListID order by Harmonica desc) rn, * from Toys
)
UPDATE CTE
SET IsPriceChg = 1 
WHERE Rn= 1

Open in new window

0
 
WorknHardrAuthor Commented:
Very nice, thx
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now