| Author |
Topic |
|
sqldba2k6
Posting Yak Master
176 Posts |
Posted - 2007-05-26 : 19:28:45
|
| Please help me in getting the output.-- Prepare sample dataDeclare @T1 table (tcol1 Int, tcol2 Int, tcol3 varchar(100), tcol4 datetime)Insert into @T1Select 5572, 1, 'test1', '2003-01-04 00:00:00.000' Union allSelect 5572, 1, 'test1', '2003-01-04 00:00:40.000' Union allSelect 5573, 1, 'tes4', '2003-01-05 00:00:00.000' Union allSelect 5574, 1, 'tes5', '2003-01-06 00:00:00.000' Union allSelect 5575, 1, 'tes6', '2003-01-06 00:00:00.000' Union allSelect 5576, 1, 'tes7', '2003-01-06 00:00:00.000'Declare @T2 table (t2col1 Int, t2col2 Int, t2col3 Datetime, t2col4 varchar(100))Insert into @T2Select 5572, 2, '2003-01-04 00:00:00.000', 'Mouse' Union allSelect 5572, 2, '2003-01-04 00:00:58.000', 'desk' Union allSelect 5573, 2, '2003-01-05 00:00:00.000', 'Mousepad' Union allSelect 5574, 2, '2003-01-06 00:00:00.000', 'Hw' union allSelect 5575, 2, '2003-01-06 00:00:00.000', 'Laptop' Declare @T3 Table (t3col1 Int, t3col2 Int, t3col3 Int, t3col4 Datetime )Insert into @T3Select 5572, 3, 09, '2003-01-04 00:00:00.000' Union allSelect 5572, 3, 10, '2003-01-04 00:00:32.000' Union allSelect 5573, 3, 40, '2003-01-05 00:00:00.000' Union allSelect 5574, 3, 65, '2003-01-06 00:00:00.000' union allSelect 5576, 3, 76, '2003-01-06 00:00:00.000'Select T1.tcol1, T1.tcol3, T2.t2col4, T3.t3col3, T1.tcol4From @T1 T1Inner join @T2 T2 on T2.t2col1 = T1.tcol1Inner join @T3 T3 on T3.t3col1 = T1.tcol1WhereT3.t3col4 = ( Select Max(t3col4) From @T3 Where t3col1 = T1.tcol1)and T2.t2col3 = ( Select Max(t2col3) From @T2 Where t2col1 = T1.tcol1)and T1.tcol4 = ( Select Max(tcol4) From @T1 Where tcol1 = T1.tcol1)Output:5572 test1 desk 10 2003-01-04 00:00:40.0005573 tes4 Mousepad40 2003-01-05 00:00:00.0005574 tes5 Hw 65 2003-01-06 00:00:00.0005575 tes6 laptop null 2003-01-06 00:00:00.0005576 tes7 null 76 2003-01-06 00:00:00.000 |
|
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2007-05-27 : 01:48:21
|
[code]select t1.tcol1, t1.tcol3, t2.t2col4, t3.t3col3, t1.tcol4from @T1 t1 left join @T2 t2 on t1.tcol1 = t2.t2col1 and t2.t2col3 = (select max(t2col3) from @T2 x where x.t2col1 = t1.tcol1) left join @T3 t3 on t1.tcol1 = t3.t3col1 and t3.t3col4 = (select max(t3col4) from @T3 x where x.t3col1 = t1.tcol1)where t1.tcol4 = (select max(tcol4) from @T1 x where x.tcol1 = t1.tcol1)order by t1.tcol1[/code] KH |
 |
|
|
sqldba2k6
Posting Yak Master
176 Posts |
Posted - 2007-05-27 : 10:20:37
|
| Thanks KH !!!With the above 3 tables please suggest the best DB relationship..Primary key/Foreign..I thought of creating theTable T1: tcol,tcol2,tcol3 composite primary key.Table T2: t2col1,t2col2,t2col3 composite primary key.Table T3: t3col1,t3col2,t3col4 composite primary key.Thanks for your help in advance. |
 |
|
|
|
|
|