日期:2014-05-18 浏览次数:20542 次
with tb as ( --把数据放到一张表里 select 1 as ID,1 as MID,13.51 as [Value],'2012-05-01' as [date],'A' as [SIGN] union all select 2,1,23.16,'2012-05-01','B' union all select 3,1,15.23,'2012-05-01','C' union all select 4,1,24.81,'2012-05-02','A' union all select 5,1,67.99,'2012-05-02','B' union all select 6,1,81.91,'2012-05-02','C' union all select 7,1,24.81,'2012-05-03','A' union all select 8,1,67.99,'2012-05-03','B' union all select 9,1,81.91,'2012-05-03','C' ) ,tb2 as ( --得到最大值,最小值,平均值 select [SIGN] , AVG(Value) as v_AvgValue, MAX(Value) as v_MaxValue, MIN(Value) as v_MinValue from tb where MID='1' and [date]='2012-05-01' --按月 where year([date])=year('时间') and month([date])=month('时间') group by [SIGN] ) --下一步,根据找到的最大值、最小值关联时间,由于最大值value出现重复,我们取最大时间 select tb2.[SIGN], tb2.v_AvgValue, tb2.v_MaxValue, max(a.date) as max_date, tb2.v_MinValue, max(b.date) as min_date from tb2 left join tb a on tb2.v_MaxValue=a.Value left join tb b on tb2.v_MinValue=b.Value group by tb2.[SIGN], tb2.v_AvgValue, tb2.v_MaxValue, tb2.v_MinValue /* SIGN v_AvgValue v_MaxValue max_date v_MinValue min_date ---- --------------------------------------- --------------------------------------- ---------- --------------------------------------- ---------- A 13.510000 13.51 2012-05-01 13.51 2012-05-01 B 23.160000 23.16 2012-05-01 23.16 2012-05-01 C 15.230000 15.23 2012-05-01 15.23 2012-05-01 (3 row(s) affected) */
------解决方案--------------------
--> 测试数据:[test] if object_id('[test]') is not null drop table [test] create table [test]( [ID] int, [MID] int