Please start any new threads on our new site at http://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | 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
 Help with Update statment
 Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

slihp
Yak Posting Veteran

61 Posts

Posted - 06/16/2014 :  14:40:04  Show Profile  Reply with Quote

Hi there

im not sure how to do this as im not great with update statements. I have a table that get populated with related ids. basically i want to periodicaly update the table and set the related ids to the last know id that was entered, so in the case below

this set

ID | LinkID | Active | Date
z5 | k2 | 0 | 01/01
s6 | k2 | 0 | 17/02
d7 | k2 | 0 | 21/03
d8 | k2 | 0 | 20/04
d9 | k2 | 1 | 02/05

would be updated to this

ID | LinkID | Active | Date
d9 | k2 | 0 | 01/01
d9 | k2 | 0 | 17/02
d9 | k2 | 0 | 21/03
d9 | k2 | 0 | 20/04
d9 | k2 | 1 | 02/05

tkizer
Almighty SQL Goddess

USA
38200 Posts

Posted - 06/16/2014 :  15:06:55  Show Profile  Visit tkizer's Homepage  Reply with Quote

--create table/sample data
create table #temp (ID char(2), LinkID char(2), Active bit, [Date] datetime)
insert into #temp values ('z5', 'k2', 0, '01/01/14')
insert into #temp values ('s6', 'k2', 0, '02/17/14')
insert into #temp values ('d7', 'k2', 0, '03/21/14')
insert into #temp values ('d8', 'k2', 0, '04/20/14')
insert into #temp values ('d9', 'k2', 1, '05/02/14')
insert into #temp values ('a4', 'k9', 0, '01/01/14')
insert into #temp values ('z8', 'k9', 1, '05/17/14')

--the part you care about
;with cte1 (LinkID, [Date])
as
(
	select LinkID, max([Date])
	from #temp
	group by LinkID
),
cte2 (ID, LinkID, [Date])
as
(
	select t.ID, cte1.LinkID, t.[Date]
	from #temp t
	join cte1
	on t.LinkID = cte1.LinkID and t.[Date] = cte1.[Date]
)
update t
set ID = cte2.ID
from #temp t
join cte2 on t.LinkID = cte2.LinkID and t.[Date] <> cte2.[Date]

--validate update
select * from #temp

--cleanup
drop ttable #temp


Tara Kizer
SQL Server MVP since 2007
http://weblogs.sqlteam.com/tarad/

Edited by - tkizer on 06/16/2014 15:08:27
Go to Top of Page
  Previous Topic Topic Next 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.03 seconds. Powered By: Snitz Forums 2000