LeetCode SQL [Hard] 1384. List total sales by year

Table-building statement and original question:

Create table If Not Exists Product (product_id int, product_name varchar(30))
Create table If Not Exists Sales (product_id varchar(30), period_start date, period_end date, average_daily_sales int)
Truncate table Product
insert into Product (product_id, product_name) values ('1', 'LC Phone ')
insert into Product (product_id, product_name) values ('2', 'LC T-Shirt')
insert into Product (product_id, product_name) values ('3', 'LC Keychain')
Truncate table Sales
insert into Sales (product_id, period_start, period_end, average_daily_sales) values ('1', '2019-01-25', '2019-02-28', '100')
insert into Sales (product_id, period_start, period_end, average_daily_sales) values ('2', '2018-12-01', '2020-01-01', '10')
insert into Sales (product_id, period_start, period_end, average_daily_sales) values ('3', '2019-12-01', '2020-01-31', '1')

 

 

 

 

 

 

 Knowledge of this question (MySQL):

1. Time function

The time function is not used much, just use the check. In this question, you need the time function to realize the first day, the last day of the year, and the number of days between the two dates.

The first day of the year: makedate (yy, days), yy uses the current year, days represents the day of the year.

The last day of the year: CONCAT (yy, '-12-31'), using string concatenation.

Time difference between two dates: datediff (day1, day2)

2. One line to multiple lines

First look at an example:

SELECT
    SUBSTRING_INDEX( SUBSTRING_INDEX('A,B,C,D,E', ',', h.help_topic_id + 1), ',',- 1 ) AS chars
FROM
    mysql.help_topic AS h 
WHERE
    h.help_topic_id < ( LENGTH('A,B,C,D,E') - LENGTH( REPLACE ('A,B,C,D,E', ',', '' ) ) + 1 );
The results of the above SQL detection are as follows


mysql.help_topic is a table that comes with mysql, h.help_topic_id is a self-increasing id, starting from 0.

After understanding this example, this question can be started.

MySQL version solution:
SELECT 
  sales.`product_id`,
  product.`product_name`,
  help_topic_id + YEAR(sales.`period_start`) AS report_year,
  DATEDIFF(
    IF(
      help_topic_id + YEAR(sales.`period_start`) < YEAR(sales.`period_end`),
      CONCAT(
        help_topic_id + YEAR(sales.`period_start`),
        '-12-31'
      ),
      sales.`period_end`
    ),
    IF(
      help_topic_id = 0,
      sales.`period_start`,
      MAKEDATE(
        YEAR(sales.`period_start`) + help_topic_id,
        1
      )
    )
  ) * sales.`average_daily_sales` + sales.`average_daily_sales` AS total_amount 
FROM
  mysql.help_topic AS h,
  sales,
  Product
WHERE h.help_topic_id < (
    YEAR(sales.`period_end`) - YEAR(sales.`period_start`) + 1
  ) AND Product.`product_id` = sales.`product_id`;

 

 

Guess you like

Origin www.cnblogs.com/onePunchCoder/p/12683519.html