简体   繁体   中英

How to find count of records by month given start and end date SQL?

I have a table:

1 180101    180228
2 180301    180831
3 180901    999999
4 180801    999999
5 180401    181031
6 181101    999999
7 180101    999999

The columns are: userid, start date, end date.

Dates are in text format, YYMMDD with 999999 meaning that there is no end date.

How do I get the number of customers for each month? Ex. March would include all customers that start on or before March, and end on or after March. But would not include customers that started in January, but ended in February.

I'm trying to do it like this, and then write out all the logic:

SELECT SUBSTRING(start_date, 3, 2) AS start, SUBSTRING(end_date, 3, 2) AS end, count(*)
FROM data
GROUP BY start, end
ORDER BY start

Was just wondering if there was any better way to do it?

If you had starts in every month, you can use correlated subqueries to get the count on the first day of the month :

select ym.yymm,
       (select count(*)
        from t
        where t.startdate <= ym.yymm and
              t.enddate >= ym.yymm
       ) as month_count
from (select distinct left(startdate, 4) as yymm
      from t
     ) ym;

Some databases might spell left() as substr() .

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