I have a table with four columns; Plant_Id, Year, Month and MR. I would like to be able to calculate the Range (month 2 month difference) of MR.
A sample of the table (MaintenanceRatebepaen is the table name) looks like this:
Plant_ID Year Month MR
CCAR 2009 1 0,706452
CCAR 2009 2 0,625899
CCAR 2009 3 0,636678
CCAR 2009 4 0,736544
CCAR 2009 5 0,552023
CCAR 2009 6 0,418338
CCAR 2009 7 0,502732
CCAR 2009 8 0,64526
CCAR 2009 9 0,743333
CCAR 2009 10 0,555556
CCAR 2009 11 0,297561
CCAR 2009 12 0,338608
CCAR 2010 1 0,380783
Etc.
I’m not sure this is of interest, but Plant_id can have 25 different values, years from 2008 – 2012, months 1-12, MR is a calculated value.
The Query looks like this:
SELECT Plant_Id, Jaar, Maand
, (SUM(Compl) + 0.000) / SUM(Total) AS MR
FROM (
SELECT Plant_Id, Jaar, Late, EarlyJobs, OnTimeJobs, Maand
, SUM(EarlyJobs + OnTimeJobs) AS Compl
, SUM(EarlyJobs) + SUM(Late) + SUM(OnTimeJobs) AS Total
FROM MaintenanceRatebepaen AS MaintenanceRatebepaen_1
GROUP BY Plant_Id, Jaar, Maand, Late, OnTimeJobs, EarlyJobs
) AS MaintenanceRatebepaen
WHERE (Jaar >= 2009) AND (Jaar <= 2011) AND (Plant_Id = 'CCAR')
GROUP BY Jaar, Plant_Id, Maand
ORDER BY Plant_Id, Jaar, Maand
I’m new to SQL, I managed to get the above from books and google searches. But I can’t get the Range calculated, any help is greatly appreciated!
Did you just want month by month differences?
Data
Query
Results:
Is that what you needed? Your query contains alot of extra columns, so I don’t know if you want that including?
* Edit *
In response to your comments, you need to put your query inside the CTE, with the additional RowNumber column. d1 and d2 are just aliases of that CTE. I think this should do it: