简体   繁体   English

Postgres复杂的SQL查询

[英]Postgres complicated SQL query

I'm trying to create a query through Postgres. 我正在尝试通过Postgres创建查询。 I have a table like this: 我有一张这样的桌子:

Date----------|Meter-----|------period-----|-----value
2017-05-23-----meter1  ---------- 1 ------------ 2.01
2017-05-23-----meter1  ---------- 3 ------------ 4.01
2017-05-23-----meter1  ---------- 4 ------------ 0.00

The table represents meter readings. 该表代表仪表读数。 There needs to be 48x meter readings per day. 每天需要有48倍的仪表读数。 However sometimes for some reason a meter reading may not come through so there will be no record. 但是有时由于某种原因可能无法读取电表读数,因此不会有记录。 Also, a meter reading could be 0.00. 此外,仪表读数可能为0.00。

What I need to do is generate a series that gives me something like this if I search for meter readings for any given meter on a particular date: 我需要做的是生成一个序列,如果我在特定日期搜索任何给定电表的电表读数,将会给我类似的东西:

Period----Total
1     ---   2.01
2     ---   null
3     ---   4.01
4     ---   0.00
.
.
.

It needs to give me 48 readings even if there is no record. 即使没有记录,它也需要给我48个读数。 I'm trying to populate a google graph from a JSON response and the graph accepts null values but not 'no' values. 我正在尝试从JSON响应填充Google图,并且该图接受null值,但不接受“ no”值。

I appreciate any help. 感谢您的帮助。

You can use generate_series to generate the numbers list and left join your table on to that and show missing periods as null . 您可以使用generate_series生成数字列表,然后将表left join在该列表上,并将缺失的期间显示为null

select g.val,t.value
from generate_series(1,48) g(val)
left join tbl on t.period=g.val and t.date = '2017-05-23' --change this value as required 

If you need it for all the dates and meters in the table, cross join generated periods with dates and meters and left join the table on to that. 如果您需要表格中的所有日期和计量表,则将日期和计量表cross join生成的期间,然后将表格与之left join

select dm.date,dm.meter,g.val,t.value
from generate_series(1,48) g(val)
cross join (select distinct date,meter from t) dm
left join t on t.period=g.val and t.date=dm.date and t.meter=dm.meter
where dm.date = date '2017-05-23' --change this value as required
and dm.meter='meter1' --change this value as required

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM