There were a couple of older posts with similar questions but none cater to my specific requirements including this one (Current month and last month data in single row).
I have a Vertica table (say CompanyData) with the following columns:
company_id | date | shares
with the PK being a composite 'company_id,date'.
Now fetching the previous month's data for a specific date or range of dates is easy enough, using add_months function. Something like:
select *
from CompanyData
where company_id = 'ABC12' and date = add_months('20121205', -1)
order by company_id, date;
However, when I want to do the same thing for the entire table (all companies, all dates) a self join is what comes to my mind.
Is there a way to avoid a join and still retrieve this information for the entire table?
Please let me know if you need any further info.
Sample table data:
company_id | date | shares
ABC12 | 20120101 | 253.77
ABC12 | 20120102 | 253.77
ABC12 | 20120103 | 254.59
ABC12 | 20120104 | 254.12
.
.
.
ABC12 | 20120201 | 257.90
ABC12 | 20120202 | 257.41
.
.
XYZ45 | 20120101 | 312.45
XYZ45 | 20120102 | 314.25
XYZ45 | 20120103 | 311.27
XYZ45 | 20120104 | 314.34
.
.
.
XYZ45 | 20120201 | 315.11
XYZ45 | 20120202 | 316.71 .
.
As mentioned earlier, we have daily frequency data for lots of companies.
Desired output would be something like:
company_id | date | shares
ABC12 | 20120101 | NULL
ABC12 | 20120102 | NULL
.
.
ABC12 | 20120201 | 253.77
ABC12 | 20120202 | 253.77
ABC12 | 20120203 | 254.59
ABC12 | 20120204 | 254.12
.
.
.
XYZ45 | 20120101 | NULL
XYZ45 | 20120102 | NULL
.
.
XYZ45 | 20120201 | 312.45
XYZ45 | 20120202 | 314.25
XYZ45 | 20120203 | 311.27
XYZ45 | 20120204 | 314.34
Thanks for your help!