Statistics according to different monthly cycles-sql

      There is now a demand: from the 26th to the 25th of each month is an enterprise month (ie: the corresponding start and end dates in February 2019 are: 2019-01-26, 2019-02-25), a product is divided into excellent products and first class Products, qualified products, unqualified products; the sum of the output of each grade of products within an enterprise month.

      The year and month at the start time and the year and month at the end time are sent from the front desk in the format: yyyy-MM. First get the 26th of the start time and the 25th of the end time.

      My own idea is: to sum up the four grades of products each month.

      That is: the start time is 2019-01, the end time is 2019-12, and check 12 times.

      Later, it was found that some functions in sql can help to deal with it, get it at once. SQL is as follows:

    select to_char(add_months(produce_date - 26,1)  ,  'yyyy-mm' ) || grade  date_grade,
        sum(yield) yield 
        from t_produce_info  
        WHERE produce_name = #{produceName} 
        and produce_date >= #{startDate,jdbcType=TIMESTAMP}
        and produce_date <= #{endDate,jdbcType=TIMESTAMP}
        group by to_char(add_months(produce_date - 26,1)  , 'yyyy-mm' ) || grade;

      To explain, first of all, produce_date is the production date, Date minus a number means minus a few days.

      The production date minus 26 can be understood as pushing all dates forward by 26 days, as long as it is the month of the enterprise, it will become between 1st and 31st.

      For example, 2019-1-30 is February according to the enterprise month, but 2019-01-04 after -26; 2019-2-24 is February according to the enterprise month, but 2019-01-30 after -26.

 

      ADD_MONTHS is an arithmetic function. The function adds a specified number of months to a date, so the day in the date is unchanged. After  add_months (produce_date-26,1) , the date becomes the day of the month corresponding to its corporate month. Use to_char, ignore the date, only keep your year and month, and then stitch up the grade, use group by classification, you can find the statistical data of each product grade of the enterprise month.

      statistical results:

 

      The only shortcoming is that if the product of this grade is not produced in the month, it cannot be queried. If someone can solve it, please contact us, WeChat: 1907797839

 

 

 

      PS: Party A changed the demand again. . . Requires January to be January 1 to January 25, June to May 26 to June 31, July to July 1 to July 25, and December to November 26 to December 31st. 

      I haven't figured out a way to get sql. . . If anyone can solve, please contact, WeChat: 1907797839

Published 48 original articles · Like 36 · Visits 130,000+

Guess you like

Origin blog.csdn.net/weixin_42845682/article/details/88353256
Recommended