我有一个MySQL tbl,有一些colums,每5分钟一次。插入一个带有3个值的新行
1. Auto inc. curent Date Unix timestamp --> date
2. power consumption absolut --> wert01
3. Power Generation absolut --> wert02
要在图表中显示此信息,对于每周功耗的示例,我需要选择已经完成的第一个和最后一个,但是必须从第一个中显示最后一个并且仅显示第二个结果&这个混蛋的日子。
SELECT
(SELECT wert01
FROM sml_splitt
WHERE date >= curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY
AND date < curdate() - INTERVAL DAYOFWEEK(curdate()) DAY
ORDER BY date DESC LIMIT 1) AS 'last',
(SELECT wert01
FROM sml_splitt
WHERE date >= curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY
AND date < curdate() - INTERVAL DAYOFWEEK(curdate()) DAY
ORDER BY date LIMIT 1) AS 'lirst
我正在寻找一些寻找解决方案的日子,但没有成功。 Hopfuly,你可以帮助我。
答案 0 :(得分:0)
如果您对查询感到满意,那么您可以再次将其嵌套一次来进行数学计算:http://sqlfiddle.com/#!9/515ef/1
select t1.last, t1.first, t1.last - t1.first as result
from (
select (
select wert01
from sml_splitt
where dt >= curdate() - interval dayofweek(curdate()) + 6 day
and dt < curdate() - interval dayofweek(curdate()) day
order by dt desc limit 1
) as 'last',
(
select wert01
from sml_splitt
where dt >= curdate() - interval dayofweek(curdate()) + 6 day
and dt < curdate() - interval dayofweek(curdate()) day
order by dt limit 1
) as 'first'
) t1
;
如果您确实希望按周使用此数据进行报告,请让我提出一些观点。第一个将为您提供所有明确的周日开始日期:
create view v1 as
select date(dt) as week_begins
from sml_splitt
where dayofweek(dt) = 1
group by week_begins
第二个视图将第一个视图与自身连接起来,为您提供一周开始和一周结束范围:
create view v2 as
select t1.week_begins, coalesce(t2.week_begins,now()) as week_ends
from v1 t1
left join v1 t2
on t2.week_begins = t1.week_begins + interval 7 day
您可以在此处查看结果:http://sqlfiddle.com/#!9/a4d1b3/2。请注意,如果本周尚未结束,我会使用now()
来获取当前日期和时间。
在那里,您可以将自己的观点与原始表格结合使用,并使用min()
和max()
功能进行分组,以获得开始和结束时间#t;&#39;值和你喜欢的任何计算。
以下是一个例子:http://sqlfiddle.com/#!9/a4d1b3/6
select week_begins, week_ends,
min(wert01) as start_wert01,
max(wert01) as end_wert01,
max(wert01) - min(wert01) as power_consumed,
min(wert02) as start_wert02,
max(wert02) as end_wert02,
max(wert02) - min(wert02) as power_generated,
(max(wert02) - min(wert02)) - (max(wert01) - min(wert01)) as net_generated
from v2
inner join sml_splitt
on sml_splitt.dt >= v2.week_begins
and sml_splitt.dt < v2.week_ends
group by week_begins
我希望有所帮助。