Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
Hommer
Aged Yak Warrior
808 Posts |
Posted - 2007-08-10 : 16:16:09
|
Hi,Could some body please help me. I want to Update tblA.colA with tblB.colA where tblB.DteDate has the min value.I remember I saw some one has a solution for this, but couldn't find it.Thanks!--create and populate #tblAIF OBJECT_ID('tempdb..#tblA') IS NOT NULL DROP TABLE #tblACREATE TABLE [#tblA] ( [PKID] INT, [colA] INT NULL) ON [PRIMARY]GOInsert INTO #tblA Values(1, 10)Insert INTO #tblA Values(2, 10)Insert INTO #tblA Values(3, 10)--create and populate #tblBIF OBJECT_ID('tempdb..#tblB') IS NOT NULL DROP TABLE #tblBCREATE TABLE [#tblB] ( [FKID] INT, [colA] INT NULL, [DteDate] datetime NULL) ON [PRIMARY]GOInsert INTO #tblB Values(1, 5, '19790222')Insert INTO #tblB Values(1, 6, '20050201')Insert INTO #tblB Values(3, 1, '20061212')--check the dataSELECT * FROM #tblASELECT * FROM #tblB--this first UPDATE wouldn't run and the second one got the wrong data, just as you can see in the SELECT, which grabbed both 5 & 6 for FKID = 1 UPDATE #tblASET colA = B.colAFROM #tblA JOIN (SELECT FKID, MIN(DteDate) AS minDte FROM #tblB GROUP BY FKID) B on #tblA.PKID = B.FKIDUPDATE #tblASET colA = B.colAFROM #tblA JOIN (SELECT FKID, colA, MIN(DteDate) AS minDte FROM #tblB GROUP BY FKID, colA) B on #tblA.PKID = B.FKIDSELECT B.*FROM #tblA JOIN (SELECT FKID, colA, MIN(DteDate) AS minDte FROM #tblB GROUP BY FKID, colA) B on #tblA.PKID = B.FKID--By the way, the solution cannot use a #table, because this will be in a UDF. |
|
ashley.sql
Constraint Violating Yak Guru
299 Posts |
Posted - 2007-08-10 : 17:00:52
|
Doh!!!!!!!!!!!!!!!!Ashley Rhodes |
 |
|
Hommer
Aged Yak Warrior
808 Posts |
Posted - 2007-08-13 : 10:43:58
|
Well, I think I need to twist the subquery in certain way...Basically, this next UPDATE is wrong in tsql syntax (the WHERE part), but it reflects the logic behind the requirement.UPDATE ASET A.colA = B.colAFROM #tblA A JOIN #tblB B ON A.PID = B.FKIDWHERE MIN(B.DteDate) = TRUEThere got to be a way around this without using #temp table or cursor. |
 |
|
Hommer
Aged Yak Warrior
808 Posts |
Posted - 2007-08-21 : 09:45:51
|
Ok, I found it.SELECT A.PKID, A.colA, B.FKID, b.colA from #tblA A join #tblB B on A.PKID = B.FKIDwhere B.DteDate in (Select min(DteDate) from #tblB Group by FKID)UPDATE #tblASET colA = B.colA from #tblA A join #tblB B on A.PKID = B.FKIDwhere B.DteDate in (Select min(DteDate) from #tblB Group by FKID)And there are another two ways to handle this in sql2000, using Top and subquery. Then in sql2005, I think, OVER() will also work. |
 |
|
|
|
|
|
|