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

求最大、最小及出现时间
SQL Server表T, 结构(日期 站点 最高 最低),字段都为文本
日期 站点 最高 最低
20000101 长沙 0001 -003
20000102 长沙 0121 0080  
20000103 长沙 0131 0050
20000104 长沙 0351 0230
 ....
20000101 湘潭 0021 0010
20000102 湘潭 0231 0002
20000103 湘潭 0121 0008
... ... ...
20000101 株洲 0021
20000102 株洲 0231
20000103 株洲 0121

要求按站点分组, 求最高、最低的最大和最小值及出现时间,如:
站点 最高 最高出现时间 最低 最低出现时间
请大家指点

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

declare @t table 
(日期 varchar(10),站点 varchar(4),最高 varchar(4),最低 varchar(4))
insert into @t
select '20000101','长沙','0001','-003' union all
select '20000102','长沙','0121','0080' union all
select '20000103','长沙','0131','0050' union all
select '20000104','长沙','0351','0230' union all
select '20000101','湘潭','0021','0010' union all
select '20000102','湘潭','0231','0002' union all
select '20000103','湘潭','0121','0008' union all
select '20000101','株洲','0021','001' union all
select '20000102','株洲','0231','002' union all
select '20000103','株洲','0121','003'

select a.站点,
a.c1 as 'max(最高)',
(select max(日期) from @t where 最高=c1 and 站点=a.站点) as 'max(最高)出现时间',
a.c2 as 'min(最高)',
(select max(日期) from @t where 最高=c2 and 站点=a.站点) as 'min(最高)出现时间',
a.c3 as 'max(最低)',
(select max(日期) from @t where 最低=c3 and 站点=a.站点) as 'max(最低)出现时间',
a.c4 as 'min(最低)',
(select max(日期) from @t where 最低=c4 and 站点=a.站点) as 'min(最低)出现时间'
from 
(
    select 站点,
    max(最高) as c1,min(最高) as c2,max(最低) as c3,min(最低) as c4
    from @t t group by 站点
) a

--我帮你改了列名和顺序,你把表名和你的对应了即可
/*
站点   max(最高) max(最高)出现时间 min(最高) min(最高)出现时间 max(最低) max(最低)出现时间 min(最低) min(最低)出现时间
---- ------- ----------- ------- ----------- ------- ----------- ------- -----------
长沙   0351    20000104    0001    20000101    0230    20000104    -003    20000101
湘潭   0231    20000102    0021    20000101    0010    20000101    0002    20000102
株洲   0231    20000102    0021    20000101    003     20000103    001     20000101
*/