LeetCode(数据库)- 按年度列出销售总额

Posted 程序员牧码

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode(数据库)- 按年度列出销售总额相关的知识,希望对你有一定的参考价值。

题目链接:点击打开链接

题目大意:略。

解题思路:略。

AC 代码

WITH t0 AS(SELECT *, DATE_FORMAT(period_start, '%Y') fromY, DATE_FORMAT(period_end, '%Y') toY  FROM Sales WHERE DATE_FORMAT(period_start, '%Y') = DATE_FORMAT(period_end, '%Y')),
t1 AS(SELECT *, DATE_FORMAT(period_start, '%Y') fromY, DATE_FORMAT(period_end, '%Y') toY FROM Sales WHERE DATE_FORMAT(period_start, '%Y') - DATE_FORMAT(period_end, '%Y') = -1),
t2 AS(SELECT *, DATE_FORMAT(period_start, '%Y') fromY, DATE_FORMAT(period_end, '%Y') toY  FROM Sales WHERE DATE_FORMAT(period_start, '%Y') - DATE_FORMAT(period_end, '%Y') = -2),

t3 AS(SELECT product_id, fromY report_year, (DATEDIFF(period_end, period_start) + 1) * average_daily_sales total_amount
FROM t0

UNION ALL 

SELECT product_id, fromY, (DATEDIFF(CONCAT(fromY, '-12-31'), period_start) + 1) * average_daily_sales total_amount
FROM t1

UNION ALL 

SELECT product_id, toY, (DATEDIFF(period_end, CONCAT(toY, '-01-01')) + 1) * average_daily_sales total_amount
FROM t1

UNION ALL 

SELECT product_id, fromY, (DATEDIFF(CONCAT(fromY, '-12-31'), period_start) + 1) * average_daily_sales total_amount
FROM t2

UNION ALL 

SELECT product_id, fromY + 1, 365 * average_daily_sales total_amount
FROM t2

UNION ALL 

SELECT product_id, toY, (DATEDIFF(period_end, CONCAT(toY, '-01-01')) + 1) * average_daily_sales total_amount
FROM t2)

SELECT CONCAT('', p.product_id) product_id, product_name, report_year, total_amount
FROM t3 JOIN Product p ON p.product_id = t3.product_id
ORDER BY product_id, report_year

以上是关于LeetCode(数据库)- 按年度列出销售总额的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode:Database 91.按年度列出销售总额

oracle 分析函数5

SQL,每个 SKU 的现金总额

如何在employee_id上 进行内部联接时获取每个唯一员工的销售总额

SQL语句统计每天、每月、每年的销售总额

LeetCode(数据库)- 按日期分组销售产品