I have a table which stores monthly billing information.
CREATE TABLE [dbo].[billing_history](
[id] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
[reading_date] [date] NOT NULL,
[reading] [numeric](18, 0) NOT NULL,
[consumer_id] [int] NOT NULL)
The consumer_id is a foreign key referencing the consumer details table.
What i want is to subtract every customer current reading from the reading of the previous month. This would generate the current bill. Any ideas.
You could use something similar to this, where you would replace the values of the month/year that you want to return:
See SQL Fiddle with Demo.
If you don’t want to pass in the values of the
monthandyearto search and you only want the current/previous month, then you could use something similar to this using a CTE:See SQL Fiddle with Demo
This version gets both the current/previous month and year values to be used. If you are not familiar with CTE syntax, this can also be written as:
See SQL Fiddle with Demo.
As you can see in my queries I used the aggregate function
SUM()and aGROUP BYon theconsumer_id. I did this in the event you had more than one reading per customer. If you know you will only have one reading per month, then you could remove the aggregate.