LeetCode SQL [Hard] 1384. 按年度列出销售总额

建表语句与原题:

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')

 

 本题知识点(MySQL):

1.时间函数

时间函数用的不多,用到查就好,本题里需要时间函数实现一年里的第一天,最后一天,以及两个日期之间相差的天数。

一年里的第一天:makedate(yy,days) ,yy 用当前年份,days代表一年的第几天。

一年的最后一天:CONCAT(yy,'-12-31') ,用字符串拼接实现。

两个日期之间的时间差 : datediff(day1,day2)

2.一行转多行

先看一个例子:

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 );
上面的SQL查出来的结果如下


mysql.help_topic 是mysql中自带的一张表,h.help_topic_id是自增id,从0开始。

理解了这个例子后本题就可以下手了。

MySQL版本题解:
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`;
 

猜你喜欢

转载自www.cnblogs.com/onePunchCoder/p/12683519.html