日期:2014-05-18  浏览次数:20417 次

很南的sql语句
有两张表 workflow(工单表)workflowhistory(工单流转历史表) id号唯一 ,每条工单的flownumber 从1开始递增。 



table workflow  
id name  
00 content  
01 content  
03 content  
table workflowhistory  

id flownumber dealtime  
00 1 2007-10-9 20:00:00  
00 2 2007-10-10 20:00:00  
01 1 2007-10-9 20:00:00  
01 2 2007-10-10 20:00:00  
03 1 2007-9-9 12:00:00 

求sql语句 把workflow workflowhistory 通过id连接起来,并且每个id只保留时间最晚的记录(或者说是flownuber最大的那条记录)id flownumber dealtime  
00 2 2007-10-10 20:00:00  
01 2 2007-10-10 20:00:00  
03 1 2007-9-9 12:00:00 



------解决方案--------------------
select * from workflowhistory where flownumber in(select Max(flownumber) from workflowhistory group by id) and id in(select id from workflow)
这么写 可以得到你想要的结果
00 2 2007-10-10 20:00:00
01 2 2007-10-10 20:00:00
03 1 2007-9-9 12:00:00
------解决方案--------------------
SQL code
select A.id,max(flownumber) as flownumber ,max(dealtime) as dealtime,max(content) as content from workflowhistory A left join workflow B on A.id = B.id group by A.id
--(所影响的行数为 3 行)
00     2    2007-10-10 20:00:00.000    content    
01     2    2007-10-10 20:00:00.000    content    
03     1    2007-09-09 20:00:00.000    content