Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

Extract total occurance of billing date within subscription period MySQL

Trying to find the number of time the billing date occurs inside the entire subscription period.

For example, if subscription period is 26-01-2015 and 24-09-2016 so the billing date is 27th of each month. Hence the query should return 20 as the number of bill cycles completed.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to make use of a MySQL number generator to generate the dates series.

Query

SELECT 
 COUNT(*) AS 'number of days'
FROM ( 

  SELECT 
   '2015-01-26' + INTERVAL generator.number DAY AS date
  FROM ( 

    SELECT 
     (@number  := @number + 1) AS number
    FROM (
      SELECT 0 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9
    ) AS record_1
    CROSS JOIN (
      SELECT 0 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9
    ) AS record_2
    CROSS JOIN (
      SELECT 0 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9
    ) AS record_3
    CROSS JOIN (
      SELECT 0 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9
    ) AS record_4
    CROSS JOIN ( SELECT @number := 0 ) AS init_user_param 
  ) AS generator
) AS dates 
WHERE 
   dates.date BETWEEN '2015-01-26' AND '2016-09-24'
 AND
   DAY(dates.date) = 27

Result

| number of days |
|----------------|
|             20 |

see demo http://sqlfiddle.com/#!9/c61cdb/9


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...