r/DatabaseHelp • • Nov 15 '16

Database schema questions.

I work at a municipal utility department in the water and wastewater treatment plants, I am building a database using data from our sensors and putting summary data into a secondary database. I have a python script that runs everyday and gets things like total plant flow for the day and saves it to the secondary database, the current schema I am using is a table called DailyData and fields of Id, Tag, Value, and Date. Each data point is a separate row. However this makes queries difficult to deal with, would it be better to have a table with all the tags as fields? We will be adding more data into the database so we would have to add fields to the table as we add data points. Or is there a better way to query the data? creating a view is difficult because we keep adding more data points.

2 Upvotes

11 comments sorted by

View all comments

Show parent comment

2

u/wolf2600 Nov 16 '16 edited Nov 16 '16

If the values are all numeric, you can do this:

SELECT Date, 
SUM(CASE WHEN Tag = 'tag1' THEN Value ELSE 0 END) as "Tag1",
SUM(CASE WHEN Tag = 'tag2' THEN Value ELSE 0 END) as "Tag2",
SUM(CASE WHEN Tag = 'tag3' THEN Value ELSE 0 END) as "Tag3",
SUM(CASE WHEN Tag = 'tag4' THEN Value ELSE 0 END) as "Tag4"
FROM DailyData
WHERE Date >= '2016-10-01'
GROUP BY Date
ORDER BY Date;

You could also use the aggregate functions MAX/MIN/AVG instead of SUM if you had multiple records of the same date and same tag.

2

u/redfrosfw Nov 16 '16

That works!! Thanks. I'm going to find some advance SQL tutorials so I can write advance queries without help.