题目
你需要为公司的营收来源生成一份年度报告。计算截止目前为止,在表格中记录的第一年和最后一年所创造的总收入百分比。将百分比四舍五入到两位小数。
示例:
输入:
annual_payments
表
列名 | 类型 |
---|---|
amount | INTEGER |
created_at | DATETIME |
status | VARCHAR |
user_id | INTEGER |
amount_refunded | INTEGER |
product | VARCHAR |
id | INTEGER |
输出:
列名 | 类型 |
---|---|
percent_first | FLOAT |
percent_last | FLOAT |
答案
解题思路: 首先找到第一年和最后一年的记录。然后,我们需要计算这些年份的总收入。最后,我们将总收入除以截止目前为止的总收入,并将结果乘以100,得到百分比。
易错点: 题目中的amount_refunded
字段是指退款金额,在计算总收入时需要将退款金额扣去。
答案代码:
SELECTROUND((SELECT SUM(amount-amount_refunded) FROM annual_paymentsWHERE YEAR(created_at) = (SELECT MIN(YEAR(created_at)) FROM annual_payments))/SUM(amount-amount_refunded) * 100.0 , 2) AS percent_first,ROUND((SELECT SUM(amount-amount_refunded) FROM annual_paymentsWHERE YEAR(created_at) = (SELECT MAX(YEAR(created_at)) FROM annual_payments))/SUM(amount-amount_refunded) * 100.0, 2) AS percent_last
FROMannual_payments;