日期:2014-05-16 浏览次数:20530 次
select SUM(n) from tableB where [time] between '' and '' and ID =(select id from tablea where stationname='')
SELECT B.ID, SUM(B.N), MAX(B.TIME), MIN(B.TIME)
FROM 表A A LEFT JOIN 表B B ON A.ID = B.ID
WHERE A.区域 = '区域1'
GROUP BY B.ID
--测试数据
create table ta (id int,stationname nvarchar(20),area nvarchar(20))
insert into ta
select 1,'站点1','区域1' union all
select 2,'站点2','区域1' union all
select 3,'站点3','区域1' union all
select 4,'站点4','区域1' union all
select 5,'站点5','区域1' union all
select 6,'站点6','区域2' union all
select 7,'站点7','区域2' union all
select 8,'站点8','区域2' union all
select 9,'站点9','区域2' union all
select 10,'站点10','区域2'
create table tb (id int,time datetime,n int)
insert into tb
select 1,'2013-1-11',10 union all
select 1,'2013-1-2',12 union all
select 1,'2013-1-3',15 union all
select 1,'2013-1-4',18 union all
select 1,'2013-1-8',25 union all
select 1,'2013-1-9',30 union all
select 2,'2013-1-1',2 union all
select 2,'2013-1-2',9 union all
select 2,'2013-1-3',15 union all
select 2,'2013-1-4',16 union all
select 2,'2013-1-5',19 union all
select 2,'2013-1-6',25 union all
select 2,'2013-1-7',30 union all
select 8,'2013-1-1',50
--结果
select SUM(n) as total,tt.id,MAX(tt.time)as '最新',MIN(tt.time) as'最旧' from (select ta.id,ta.stationname,tb.time,tb.n from ta inner join tb on ta.id=tb.id and ta.area='区域1' )tt where tt.time between '2013-1-2' and '2013-1-7' group by tt.id
SELECT t.stationname ,t.id ,t.bigTime , bb.n ,t.minTime , cc.n
FROM ( SELECT MAX(TIME) bigTime , MIN(TIME) minTime , a.id , a.stationname
FROM ta a INNER JOIN TB b ON a.id = b.id AND a.area = '区域1'
WHERE b.TIME BETWEEN '2013-01-02' AND '2013-01-07'