Re: [SQL ] 如何实作"状态"的query

楼主: cutekid (可爱小孩子)   2017-06-29 18:06:22
网址: http://rextester.com/WBP97001
SQL:
create TABLE myTable_test(
type char(1),
value int,
spec int,
time char(6),
switch int
);
insert into myTable_test select 'A',20,21,'6月20日',0;
insert into myTable_test select 'A',22,21,'6月21日',0;
insert into myTable_test select 'A',20,21,'6月22日',0;
insert into myTable_test select 'A',20,21,'6月22日',0;
insert into myTable_test select 'A',22,21,'6月26日',0;
insert into myTable_test select 'A',20,21,'6月27日',0;
insert into myTable_test select 'B',11,12,'6月13日',0;
insert into myTable_test select 'B',11,12,'6月13日',0;
insert into myTable_test select 'B',11,12,'6月13日',0;
insert into myTable_test select 'B',22,12,'6月15日',0;
insert into myTable_test select 'B',13,12,'6月18日',0;
insert into myTable_test select 'B',13,12,'6月19日',0;
##############
# value > spec
update myTable_test
set switch = 1
where value > spec;
############
# 1. 同 type
# 2. 令 switch = 1 出现的最小时间点为 x
# 3. 将 time >= x 的 switch 都设为 1
update myTable_test as t1
inner join (
select type,min(time) as time
from myTable_test
where switch = 1
group by type
) as t2 on t1.type = t2.type and t1.time >= t2.time
set t1.switch = 1;
##########
# 搜寻结果
select * from myTable_test;
drop table myTable_test;
※ 引述《jord98972005 (旧的)》之铭言:
: 数据库名称:MySQL
: 数据库版本:
: 内容/问题描述:
: TYPE Value SPEC Time SWITCH
: A 20 21 6月20日 0
: A 22 21 6月21日 1
: A 20 21 6月22日 1
: A 20 21 6月22日 1
: A 22 21 6月26日 1
: A 20 21 6月27日 1
: B 11 12 6月13日 0
: B 11 12 6月13日 0
: B 11 12 6月13日 0
: B 22 12 6月15日 1
: B 13 12 6月18日 1
: B 13 12 6月19日 1
: TABLE如上,Value是量测资料,当value超过安全值(spec)之后,switch切换成1
: 同一type之后时间点的资料都switch=1
: 变到typeB时又重新把switch归0重新计算
: 想了很久不知道是要用什么实作,C的话应该两个if 就能解决了

Links booklink

Contact Us: admin [ a t ] ucptt.com