56,679
社区成员
发帖
与我相关
我的任务
分享
mysql> select * from tbl;
+------+--------+-------+---------------------+-----------+
| id | group1 | obj | date_time | obj_value |
+------+--------+-------+---------------------+-----------+
| 1 | 一楼 | 房间1 | 2010-12-01 00:00:00 | 10 |
| 2 | 一楼 | 房间2 | 2010-12-01 00:00:00 | 15 |
| 3 | 一楼 | 房间3 | 2010-12-01 00:00:00 | 15 |
| 4 | 二楼 | 房间1 | 2010-12-01 00:00:00 | 20 |
| 5 | 二楼 | 房间2 | 2010-12-01 00:00:00 | 10 |
| 6 | 一楼 | 房间1 | 2010-12-01 23:00:00 | 20 |
| 7 | 一楼 | 房间2 | 2010-12-01 23:00:00 | 25 |
| 8 | 一楼 | 房间3 | 2010-12-01 23:00:00 | 20 |
| 9 | 二楼 | 房间1 | 2010-12-01 23:00:00 | 30 |
| 10 | 二楼 | 房间2 | 2010-12-01 23:00:00 | 20 |
+------+--------+-------+---------------------+-----------+
10 rows in set (0.00 sec)
mysql> select group1,
-> Sum(if(date_time=(select max(date_time) from tbl where group1=a.group1),obj_value,0)) As max_value,
-> Sum(if(date_time=(select min(date_time) from tbl where group1=a.group1),obj_value,0)) as min_value,
-> Sum(if(date_time=(select max(date_time) from tbl where group1=a.group1),obj_value,0))
-> -sum(if(date_time=(select min(date_time) from tbl where group1=a.group1),obj_value,0)) As cha_value
-> from tbl a
-> group by group1;
+--------+-----------+-----------+-----------+
| group1 | max_value | min_value | cha_value |
+--------+-----------+-----------+-----------+
| 一楼 | 65 | 40 | 25 |
| 二楼 | 50 | 30 | 20 |
+--------+-----------+-----------+-----------+
2 rows in set (0.00 sec)
mysql>
create table tbl(
id int, group1 varchar(30), obj varchar(30), date_time datetime, obj_value int)
insert into tbl values
(1 ,'一楼','房间1',' 2010-12-01 00:00:00', 10),
(2 ,'一楼','房间2',' 2010-12-01 00:00:00', 15),
(3 ,'一楼','房间3',' 2010-12-01 00:00:00',15),
(4 ,'二楼','房间1',' 2010-12-01 00:00:00', 20),
(5 ,'二楼','房间2',' 2010-12-01 00:00:00', 10),
(6 ,'一楼','房间1',' 2010-12-01 23:00:00', 20 ),
(7 ,'一楼','房间2',' 2010-12-01 23:00:00', 25),
(8 ,'一楼','房间3',' 2010-12-01 23:00:00', 20),
(9 ,'二楼','房间1',' 2010-12-01 23:00:00', 30),
(10,'二楼','房间2',' 2010-12-01 23:00:00', 20)
select group1,date_time,max(a.Num) as MAX_VALUE,min(a.Num) as MIN_VALUE,max(a.Num)-min(a.Num) as CHA_VALUE
from(
select group1,date_time,sum(obj_value) as Num from tbl group by group1,date_time ) a
group by group1
mysql> select group1,date_time,max(a.Num) as MAX_VALUE,min(a.Num) as MIN_VALUE,max(a.Num)-min(a.Num) as CHA_VALUE
-> from(
-> select group1,date_time,sum(obj_value) as Num from tbl group by group1,date_time ) a
-> group by group1;
+--------+---------------------+-----------+-----------+-----------+
| group1 | date_time | MAX_VALUE | MIN_VALUE | CHA_VALUE |
+--------+---------------------+-----------+-----------+-----------+
| 一楼 | 2010-12-01 00:00:00 | 65 | 40 | 25 |
| 二楼 | 2010-12-01 00:00:00 | 50 | 30 | 20 |
+--------+---------------------+-----------+-----------+-----------+
2 rows in set (0.00 sec)
mysql>