I have two tables Keywords, ProjectReports:
http://sqlfiddle.com/#!15/06ae3/1
As you can see in that example everything works fine, but I want to get more data from those 2 tables and I don't know how.
- In the
position
column I would like to display only the smallest value and just one value instead of that array. ex: [1, 2, 3] will be 1 - As you can see there is the
keyword
withid 4
which doesn't have any data in theproject_reports
table, in this case I would like to add thevalue 0
in theposition column
and add the current day date in theCREATED_AT
column. - Also I would like to display the position value for the same keywords, where
created_at
column fromproject_reports
table had the valuenow() - interval '1 day'; now() - interval '1 week'; now() - interval '1 mon'
, if there is noposition
for those days add0
.
Expected output:
Keywords:
ID: 1 name: test
ID: 2 name: test1
ID: 3 name: test2
Project_reports:
ID: 1, keyword_id: 1, project_id: 1, position: 1, created_at: '2014-07-09'
ID: 2, keyword_id: 1, project_id: 1, position: 2, created_at: '2014-07-09'
ID: 3, keyword_id: 1, project_id: 1, position: 3, created_at: '2014-07-10'
ID: 5, keyword_id: 1, project_id: 1, position: 4, created_at: '2014-07-10'
ID: 6, keyword_id: 2, project_id: 1, position: 1, created_at: '2014-07-09'
After query
k_name: test, k_id: 1, p_id: 1, position 3, yesterday_position: 1, created_at: '2014-07-10'
k_name: test1, k_id: 2, p_id: 1, position 0, yesterday_position: 1, created_at: '2014-07-10'
k_name: test2, k_id: 3, p_id: 1, position 0, yesterday_position: 0, created_at: '2014-07-10'
k_name: test, k_id: 1, p_id: 1, position 1, yesterday_position: 0, created_at: '2014-07-09'
k_name: test1, k_id: 2, p_id: 1, position 1, yesterday_position: 0, created_at: '2014-07-09'
k_name: test2, k_id: 3, p_id: 1, position 0, yesterday_position: 0, created_at: '2014-07-09'
Best Answer
Note the slightly modified schema of my test in the fiddle.
Using actual primary keys and proper column names instead of
id
.Also, you seem to be operating with dates exclusively. So I suggest to convert your
timestamp
columns todate
.Items 1 and 2
GROUP BY
.COALESCE
to replace possibleNULL
values.A guess at item 3
Explain
cte
produce daily aggregates per(k.keyword_id, pr.project_id)
.x
pick the latest day per(k.keyword_id, pr.project_id)
.LEFT JOIN
the latest dayx
tocte
multiple times to retrieve past values from the same(k.keyword_id, pr.project_id)
for 1 day / week / month earlier.SQL Fiddle.