SQLserver 关于 left join group by 等用法笔记

数据库环境: SQLserver 2008 r2,  

系统环境:window server 2003

数据表  主表 PROJ_ID_ ,子表 PW_PROJ_DISCLOSE,PW_PROJ_FEEDBACK, PW_PROJ_CHANGE,PW_PROJ_COMPLETE



表状态:主表数据不变,子表可以随意增删,

需求:做一个总查询,查询子表的所有字段和总表的某些字段, 子表外键PROJ_ID_=主表主键 ID_,主表ID唯一(只出现一次),所有数据只取最新一条


需要用到字段:DOC_CREATED_   每个表都有的字段 由框架自动生成 ,表示当前数据插入的具体日期时间(可以说唯一)


难点盲点:mssql的group by 和 mysql的group by 用法不同  前者查询 的字段必须要包含在聚合函数中(自己查)


自己写的:

select  ##############################################################

						from  PW_PROJ_ p 
								left join  PW_PROJ_DISCLOSE p1 on p1.PROJ_ID_=p.ID_
								left join PW_PROJ_FEEDBACK p2 on p1.PROJ_ID_=p2.PROJ_ID_ 

								left join PW_PROJ_CHANGE p3 on p1.PROJ_ID_=p3.PROJ_ID_  
								left join PW_PROJ_COMPLETE p4 on p1.PROJ_ID_=p4.PROJ_ID_
								
						where  p1.DOC_CREATED_=(select max(in_p1.DOC_CREATED_)
																from PW_PROJ_DISCLOSE in_p1  
																where PROJ_ID_=p1.PROJ_ID_ group by in_p1.PROJ_ID_)
						and p2.DOC_CREATED_=(select max(in_p2.DOC_CREATED_)
																from PW_PROJ_FEEDBACK in_p2  
																where PROJ_ID_=p2.PROJ_ID_ group by in_p2.PROJ_ID_)
						and p3.DOC_CREATED_=(select max(in_p3.DOC_CREATED_)
																from PW_PROJ_CHANGE in_p3 
																where PROJ_ID_=p3.PROJ_ID_ group by in_p3.PROJ_ID_)
						and p4.DOC_CREATED_=(select max(in_p4.DOC_CREATED_)
																from PW_PROJ_COMPLETE in_p4  
																where PROJ_ID_=p4.PROJ_ID_ group by in_p4.PROJ_ID_)
                                               

少颖写的,即使子表没有该外键,主表所有信息都显示出来,其他没信息的字段为空

  select ######################             from  PW_PROJ_ p 
								left join  (select *   
											from PW_PROJ_DISCLOSE in_p1,(select max(in_in_p1.DOC_CREATED_) as d1 
																	     from PW_PROJ_DISCLOSE in_in_p1 group by in_in_p1.PROJ_ID_) in_p1_other										
											where in_p1.DOC_CREATED_ = in_p1_other.d1) p1
								on p1.PROJ_ID_=p.ID_
								left join  (select *   
											from PW_PROJ_FEEDBACK in_p2,(select max(in_in_p2.DOC_CREATED_) as d1 
																	     from PW_PROJ_FEEDBACK in_in_p2 group by in_in_p2.PROJ_ID_) in_p2_other										
											where in_p2.DOC_CREATED_ = in_p2_other.d1) p2
								on p2.PROJ_ID_=p.ID_  
								left join  (select *   
											from PW_PROJ_CHANGE in_p3,(select max(in_in_p3.DOC_CREATED_) as d1 
																	     from PW_PROJ_CHANGE in_in_p3 group by in_in_p3.PROJ_ID_) in_p3_other										
											where in_p3.DOC_CREATED_ = in_p3_other.d1) p3
								on p3.PROJ_ID_=p.ID_
								left join  (select *   
											from PW_PROJ_COMPLETE in_p4,(select max(in_in_p4.DOC_CREATED_) as d1 
																	     from PW_PROJ_COMPLETE in_in_p4 group by in_in_p4.PROJ_ID_) in_p4_other										
											where in_p4.DOC_CREATED_ = in_p4_other.d1) p4
								on p4.PROJ_ID_=p.ID_


 
 

你可能感兴趣的:(笔记,sql,sql,server,2008,左查询+条件,group,by)