Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
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.
Hi we have more than 1 tables that has lastupdateddatetime column. how can I find out a user's last time entered in system. Thanks!we are using sql server 2005 version
sunitabeck
Master Smack Fu Yak Hacker
5155 Posts
Posted - 2012-01-05 : 17:25:54
I think the simplest may be to union results from all the relevant tables and then pick the max out of that.
SELECT userId, MAX(MaxUpdateTime) AS MaxUpdateTimeFROM( SELECT userId, MAX(updatetime) AS MaxUpdateTime FROM Table1 GROUP BY userId UNION ALL SELECT userId, MAX(updatetime) AS MaxUpdateTime FROM Table2 GROUP BY userId UNION ALL SELECT userId, MAX(updatetime) AS MaxUpdateTime FROM Table3 GROUP BY userId) sGROUP BY userId;
bluemagic74
Starting Member
15 Posts
Posted - 2012-01-09 : 15:31:05
Thanks. This query works ,but I am getting more than 1 row for user. How to get only very last Updated time per user.
X002548
Not Just a Number
15586 Posts
Posted - 2012-01-09 : 15:33:55
quote:Originally posted by bluemagic74 Thanks. This query works ,but I am getting more than 1 row for user. How to get only very last Updated time per user.
Here you goCREATE TABLE [dbo].[Table1]( [USER_NB] [int] NOT NULL, [LSTUPDT_TS] [datetime] NOT NULL)CREATE TABLE [dbo].[Table2]( [USER_NB] [int] NOT NULL, [LSTUPDT_TS] [datetime] NOT NULL)CREATE TABLE [dbo].[Table3]( [USER_NB] [int] NOT NULL, [LSTUPDT_TS] [datetime] NOT NULL)USER_NB LSTUPDT_TS1 11/20/07 6:042 11/21/07 6:091 11/22/07 7:0610 11/23/07 6:251 11/24/07 6:475 11/25/07 7:202 11/26/07 4:585 11/27/07 6:092 11/28/07 6:161 11/29/07 6:183 11/29/07 18:583 11/30/07 6:42I am running below query to get very last updated date time.SELECT USER_NB, Max(MaxUpdateTime)FROM( SELECT USER_NB, MAX(LSTUPDT_TS) AS MaxUpdateTime FROM Table1 GROUP BY USER_NB UNION ALL SELECT USER_NB, MAX(LSTUPDT_TS) AS MaxUpdateTime FROM Table 2 GROUP BY USER_NB UNION ALL SELECT USER_NB, MAX(LSTUPDT_TS) AS MaxUpdateTime FROM Table 3 GROUP BY USER_NB ) sGROUP BY S.USER_NB, s.MaxUpdateTimeBut the output shows more than one row per user. Thanks
sunitabeck
Master Smack Fu Yak Hacker
5155 Posts
Posted - 2012-01-10 : 06:59:01
Remove the grouping on the MaxUpdateTime.
SELECT USER_NB, Max(MaxUpdateTime)FROM(SELECT USER_NB, MAX(LSTUPDT_TS) AS MaxUpdateTime FROM Table1 GROUP BY USER_NBUNION ALLSELECT USER_NB, MAX(LSTUPDT_TS) AS MaxUpdateTime FROM Table 2 GROUP BY USER_NBUNION ALLSELECT USER_NB, MAX(LSTUPDT_TS) AS MaxUpdateTime FROM Table 3 GROUP BY USER_NB) sGROUP BY S.USER_NB , s.MaxUpdateTime