SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Variable update
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

AlanPD
Starting Member

2 Posts

Posted - 05/08/2012 :  07:24:51  Show Profile  Reply with Quote
I want to write an update query to add a reference based on the date of an order item. So that all Items with the earliest date for that order have a reference of 1, items with the next date are 2 and so on.
Eg.
Order, - Item, - Date, ---- Reference
0001 --- 01 ---- 01/01/01 - 1
0001 --- 02 ---- 01/01/01 - 1
0001 --- 03 ---- 01/02/01 - 2
0002 --- 01 ---- 01/03/01 - 1

Is it possible to create an update statement which iterates through the records setting a values which is determined by the values in previous records?

sunitabeck
Flowing Fount of Yak Knowledge

5152 Posts

Posted - 05/08/2012 :  07:31:40  Show Profile  Reply with Quote
You can use RANK or DENSE_RANK function - probably in your case you need DENSE_RANK.
SELECT
	*,
	DENSE_RANK() OVER(PARTITION BY ORDER ORDER BY [Date]) AS Reference
FROM
	YourTable
If you already have a column in your table named Reference that is null now and want to update that column, you can do it like this:
;with cte as
(
	SELECT
		*,
		DENSE_RANK() OVER(PARTITION BY ORDER ORDER BY [Date]) AS NewReference
	FROM
		YourTable
)
UPDATE cte SET Reference = NewReference;
Go to Top of Page

AlanPD
Starting Member

2 Posts

Posted - 05/08/2012 :  09:05:40  Show Profile  Reply with Quote
Excellent answer, thank you very much.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

India
47023 Posts

Posted - 05/08/2012 :  11:20:24  Show Profile  Reply with Quote
Using Apply operator

UPDATE t
SET Reference = COALESCE(t1.Cnt,0) + 1
FROM YourTable t
OUTER APPLY (SELECT COUNT(DISTINCT Date) AS Cnt
             FROM YourTable
             WHERE Order= t.Order
             AND Date < t.Date
             )t1


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/


Edited by - visakh16 on 05/08/2012 11:20:43
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.06 seconds. Powered By: Snitz Forums 2000