I have specific date range like
From Date To Date
---------------------------
2012-11-10 2012-11-15
2012-11-21 2012-11-22
2012-11-30 2012-12-01
I want to write a SQL query which calculates the total no of days between two dates and sum total number of days of particular month
The output I wanted is,
No of days month
--------------------
9 11
1 12
Can anyone help me to write this SQL query?
Ideally, you have a table named “Dates” with all the dates you will ever use, e.g. year 1950 through 2100. This query will give you the result you want:
Result:
Note that instead of just showing “11” or “12” as month, which doesn’t work well if you have ranges going above 12 months, or doesn’t help sorting when it crosses a new year, this query shows the first day of the month instead.
If not, you can virtually create a
datestable on the fly, per the expanded query below:The full working sample is given here: SQL Fiddle