22,209
社区成员
发帖
与我相关
我的任务
分享
if object_id('[TB_1]') is not null drop table [TB_1]
go
create table [TB_1] (BuildingID int,time datetime,value int)
insert into [TB_1]
select 1,'2011/4/30 23:00',1 union all
select 1,'2011/5/1 00:00',1
if object_id('[TB_2]') is not null drop table [TB_2]
go
create table [TB_2] (BuildingID int,time datetime,fengValue int,guValue int,pingValue int)
insert into [TB_2]
select 1,'2011/1/1',1,2,3 union all
select 1,'2011/5/1',2,4,6
select * from [TB_1]
select * from [TB_2]
SELECT A.BuildingID ,
A.time AS 日期时间 ,
MAX(B.time) AS 收费时限 ,
( CASE WHEN CONVERT(TIME, A.[time]) BETWEEN '5:00' AND '9:00' --时间自己调整一下
THEN MAX(B.fengValue)
ELSE CASE WHEN CONVERT(TIME, A.[time]) BETWEEN '16:00' AND '23:59'
THEN MAX(B.guValue)
ELSE CASE WHEN CONVERT(TIME, A.[time]) BETWEEN '9:00' AND '16:00'
THEN MAX(B.pingValue)
ELSE CASE WHEN CONVERT(TIME, A.[time]) BETWEEN '0:00' AND '5:00'
THEN MAX(B.guValue)
END
END
END
END ) * A.value AS cost
FROM [TB_1] A
INNER JOIN [TB_2] B ON A.time >= B.time
GROUP BY A.BuildingID ,
A.time ,
A.value
/*
BuildingID 日期时间 收费时限 cost
----------- ----------------------- ----------------------- -----------
1 2011-04-30 23:00:00.000 2011-01-01 00:00:00.000 2
1 2011-05-01 00:00:00.000 2011-05-01 00:00:00.000 4
(2 行受影响)*/
select
a.BuildingID,
sum(case when time between 'xx' and 'xx' then fengValue
when time between 'xx' and 'xx' then guValue
when time between 'xx' and 'xx' then pingValue
end)*a.value
from
电能耗表 a join 电价信息表 b
on
a.BuildingID=b.BuildingID
where
a.time between 'xx' and 'xx'
group by
a.BuildingID
select
a.BuildingID,
sum(case when time between 'xx' and 'xx' then fengValue
when time between 'xx' and 'xx' then guValue
when time between 'xx' and 'xx' then pingValue
end)*a.value
from
电能耗表 a join 电价信息表 b
on
a.BuildingID=b.BuildingID
group by
a.BuildingID