btcj 发表于 2010-8-24 15:19

SQL查询语句求助

现有下表:
stationID     observTime        TT    Ta    Tatime
   A      2010-7-15 15:00:00    261   267    1901
   B      2010-7-15 15:00:00    234   245    2342
   B      2010-7-15 14:00:00    226   254    3532
   A      2010-7-15 14:00:00    207   212    0907
   A      2010-7-15 13:00:00    231   243    3724
   B      2010-7-15 13:00:00    242   237    2529
   A      2010-7-15 12:00:00    211   227    2438

要查出每一个站点(stationID)在2010-7-15 13:00:00到2010-7-15 14:00:00(observTime)时间段内Ta最大值及最大值所对应的observTime,Tatime列相应值,即查出下表的结果
stationID     observTime          Ta    Tatime
   A      2010-7-15 13:00:00      243    3724
   B      2010-7-15 14:00:00      254    3532

应如何写SQL语句?


[[i] 本帖最后由 btcj 于 2010-8-24 15:20 编辑 [/i]]

红色警戒 发表于 2010-8-24 16:06

分步查询吧,先查询出不同的站点名称,再根据查询各个站点时间段的最大值和时间

aei135 发表于 2010-8-24 17:17

select a.stationid,a.observtime,a.ta,a.tatime from table a inner join
(select stationid,max(ta) mta from table where observtime between '2010-7-15 13:00:00' and '2010-07-15 14:00:00' group by stationid) b
on a.stationid=b.stationid and a.ta=b.mta

btcj 发表于 2010-8-25 12:53

楼上的语句试了,不正确,会输出重复的站点,且挑选出来的值时间不在规定的时间内

aei135 发表于 2010-8-25 15:14

输出重复站点应该是你最大的ta值有重复,但没有完全相同的行,要让他不重复,必须定个优先规则才行,不然肯定会重复,时间不在指定范围内是忘了最后加条件过滤了,呵呵!
select a.stationid,a.observtime,a.ta,a.tatime from table a inner join
(select stationid,max(ta) mta from table where observtime between '2010-7-15 13:00:00' and '2010-7-15 14:00:00' group by stationid) b
on a.stationid=b.stationid and a.ta=b.mta  
WHERE a.observtime between '2010-7-15 13:00:00' and '2010-7-15 14:00:00'

qingshuiliu 发表于 2010-8-25 16:19

路过看看

btcj 发表于 2010-8-25 16:54

最大的ta值的确是有重复,加了时间条件后输出结果正确,谢谢!

筱晓绾 发表于 2010-9-4 11:15

[tk34]路过看看

张丹 发表于 2010-9-8 15:44

select distinct(stationID), observtime,tatime from table where observTime between '2010-7-15 13:00:00' and '2010-7-15 14:00:00' group by stationid
这样应该也可以

我真是木小板 发表于 2010-9-9 08:52

哇。很有意思。`

bmw250 发表于 2010-10-11 08:54

新手来学习一下的[em04]

s1012110700 发表于 2010-10-11 11:14

路过看下

tangyunzhong 发表于 2010-10-11 17:56

这个问题好像很简单的,上面的代码我看了一些,但是觉得代码太长了.
楼主可以试一下我的语句.
select max(stationID) as stationID,max(observTime) as observTime,max(ta) as ta,max(Tatime) as tatime from 表
where observTime between '2010-7-15 13:00:00' and '2010-07-15 14:00:00'
group by stationID

页: [1]

编程论坛