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

求一SQL,望指点啊
表结构如下t_Temp

ID[自增] MID Value Date[datetime类型] SIGN
1 1 13.51 2012/05/01 A 
2 1 23.16 2012/05/01 B 
3 1 15.23 2012/05/01 C 
4 1 24.81 2012/05/02 A 
5 1 67.99 2012/05/02 B 
6 1 81.91 2012/05/02 C 
7 1 24.81 2012/05/03 A 
8 1 67.99 2012/05/03 B 
9 1 81.91 2012/05/03 C
... ... .... .... .
17 1 24.81 2012/06/01 A 
18 1 67.99 2012/06/01 B 
19 1 81.91 2012/06/01 C  
20 2 13.51 2012/05/01 A 
21 2 23.16 2012/05/01 B
22 2 15.23 2012/05/01 C  


要求根据MID查询出“MID = 1”AND 日期等于“某一天”的数据,
查询结果格式如下
SIGN Value[平均值] Value[最大值] Value[最大值所在的时间点] Value[最小值] Value[最小值所在的时间点]
 A ... ... date ... date
 B ... ... date ... date
 C ... ... date ... date
 

另外如果上述的查询结果条件是“MID = 1”AND 日期等于“某一月”又该如何计算?

求教


------解决方案--------------------
SQL code

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)
*/

------解决方案--------------------
SQL code

--> 测试数据:[test]
if object_id('[test]') is not null 
drop table [test]
create table [test](
[ID] int,
[MID] int