简体   繁体   中英

Find days between two dates in each Quarter

I have two date columns in table (SQLITE)

Now what i need is to find number days appear in each quarter between these two dates

For example let's say,

start_Date = 12-Jan-2015
end_Date = 13-Jul-2015

So result should be like:

Quarter 1 = 79 days
Quarter 2 = 91 days
Quarter 3 = 13 days
Quarter 4 = 0 days

I have tried below query

SELECT CASE WHEN cast(strftime('%%m', end_date) as integer) BETWEEN 1 AND 3 THEN 'Q1' WHEN cast(strftime('%%m', end_date) as integer) BETWEEN 4 and 6 THEN 'Q2' WHEN cast(strftime('%%m', end_date) as integer) BETWEEN 7 and 9 THEN 'Q3' ELSE 'Q4' END as Quarter, sum(julianday(end_date) - julianday(start_date) + 1) AS Total FROM table WHERE end_date BETWEEN '2015-01-01 00:00:00' AND '2015-12-31 00:00:00' GROUP BY Quarter

But problem is it will show all days in Quarter considering end_date. So if end_date's month is 4 then all days will be displayed in Quarter 3.

Any suggestions are welcomed. Either is sqlite query only, or in ios SDK or use of both. In any scenario possible.

Thanks....!!

This is going to be unwieldy to do in SQL, but given that you tagged this with NSDateComponents , it looks like you know the basic techniques you need. Use the NSDateComponents methods provided by NSCalendar :

  • Use component:fromDate: to get the year.

  • Calculate the start of Q1 by using components of month of 1, day of 1, and the previously determined year and calling dateFromComponents: .

  • Now loop through:

    • Calculate the start of the next quarter by adding three months to the start of the quarter using dateByAddingUnit (or dateByAddingComponents if you need to support older OS versions).

    • Look at start and end dates, comparing them to the start and end of the quarter, to figure out how many days occur with this particular quarter (you can use components:fromDate:toDate:options: to count the number of days).

    • Repeat this for the next quarter.

Those are the basic steps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM