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

急,请高手回答!
有俩表,A表customid,execdate,billcode(值只有whl这一个)
              B表customid,execdate,billcode(值只有csp这一个)

              现在我想得到每个customid的最大的execdate,每个客户的whl这种业务的最大的execdate,每个客户的csp这种业务的最大的execdate,
              只用查询来实现(不用update的办法)

------解决方案--------------------
----创建测试数据
declare @t table(customid int,execdate datetime,billcode varchar(10))
insert @t
select 1, '2007-07-01 ', 'whl ' union all
select 1, '2007-07-02 ', 'whl ' union all
select 2, '2007-07-03 ', 'whl ' union all
select 2, '2007-07-04 ', 'whl ' union all
select 1, '2007-07-05 ', 'csp ' union all
select 1, '2007-07-06 ', 'csp ' union all
select 2, '2007-07-07 ', 'csp ' union all
select 3, '2007-07-08 ', 'csp '

----查询
select a.customid, max(a.execdate) as max_execdate,
(select max(execdate) from @t where billcode = 'whl ' and customid = a.customid) as max_whl,
(select max(execdate) from @t where billcode = 'csp ' and customid = a.customid) as max_csp
from @t as a
group by a.customid
order by a.customid

/*结果
customid max_execdate max_whl max_csp
-----------------------------------------------
1 2007-07-06 00:00:00.000 2007-07-02 00:00:00.000 2007-07-06 00:00:00.000
2 2007-07-07 00:00:00.000 2007-07-04 00:00:00.000 2007-07-07 00:00:00.000
3 2007-07-08 00:00:00.000 NULL 2007-07-08 00:00:00.000
*/