难倒牛人无数!select id,isnull(select max(mydate) from table2 where id=table1.id,null)
select   id,isnull(select   max(mydate)   from   table2   where   id=table1.id,null)      
 表table2如下:   
 id,   mydate,   name 
 1200,      4,      A 
 1200,      5,      B 
 1200,      7,      C 
 1200,      6,      D     
 如果按照上面的写法,那么将返回:     
 id,   mydate,   name 
 1200,      7,      A 
 1200,      7,      B 
 1200,      7,      C 
 1200,      7,      D   
 我只想要一行结果(假设给id=1200),即mydate最大值的那行结果: 
 1200,      7,      C   
 不知道这条语句应该如何改呢?(由于table1和table2要连接,所以一定要用到ISNULL,来返回所有table1里的id。换句话说就是table2里面不一定含有table1里面的id,如果是这样就返回id,null,null)
------解决方案--------------------create table table1(id int) 
 create table table2(id int, mydate int,name char(1))   
 insert table1 values(1200) 
 insert table1 values(1300)   
 insert table2 values(1200,      4   ,       'A ') 
 insert table2 values(1200 ,      5   ,       'B ') 
 insert table2 values(1200 ,      7   ,        'C ') 
 insert table2 values(1200      ,6  ,        'D ')   
 declare @id int 
 select @id = 1200 
 select table1.id,mydate,name from table2,table1 
 where table2.id =* table1.id and table2.mydate = (select max(a.mydate)  from table2 a,table1 b where a.id =* b.id and b.id =  @id) 
 and table1.id = @id 
 id          mydate      name  
 ----------- ----------- ----  
 1200        7           C   
 (所影响的行数为 1 行) 
 @id 取1300时 
 id          mydate      name  
 ----------- ----------- ----  
 1300        NULL        NULL   
 (所影响的行数为 1 行)     
------解决方案--------------------你這裏沒有講table1的結構如何,如果table1是一個以ID為主鍵的表(每ID一條,ID的數量> =table2中所使用ID的數量),可以這麽做: 
 數據準備: 
 create table t1(id int primary key); 
 create table t2(id int,mydate int,[name] varchar(10)); 
 insert into t1 values (1); 
 insert into t1 values (2); 
 insert into t1 values (3); 
 insert into t1 values (4); 
 insert into t2 values (1,7, 'A '); 
 insert into t2 values (1,6, 'B '); 
 insert into t2 values (3,9, 'C '); 
 insert into t2 values (3,1, 'A '); 
 insert into t2 values (3,11, 'D ');   
 查詢: 
 Select t1.ID , t2.mydate, t2.name From t1 Left Join ( 
     Select t2.* From t2 Join ( 
         Select ID,Max(mydate) mydate From t2 Group By ID 
     ) t2Tmp On t2.ID=t2Tmp.ID And t2.mydate=t2Tmp.mydate 
 ) t2 On t1.ID=t2.ID   
 結果: 
 id       mydate     name 
 ------------------------- 
 1   	7          A 
 2        NULL       NULL 
 3        11         D 
 4        NULL       NULL   
 SQL共有5行,兩次包裝,第2行-第4行可單獨使用,它在t2表上進行自連接實現按ID選取MYDATE列最大的一行資料,形成的結果集再與T1進行左聯從而達到效果。
------解决方案--------------------看下
------解决方案--------------------多给分,讲清楚,提供资料充分
------解决方案--------------------  select a.id,isnull(mydate,0) mydate,isnull(name,null) name from t1 a left join 
 ( 
 select id,mydate,name 
 from t2 a 
 where not exists(select id from t2 where id=a.id and mydate> a.mydate group by id) 
 ) b on a.id=b.id     
 LZ说话自相矛盾,不是说不能用函数,那你还用ISNULL?