gpt4 book ai didi

Mysql根据条件计算列值

转载 作者:行者123 更新时间:2023-11-30 21:58:54 25 4
gpt4 key购买 nike

我有一个表,其中包含 daymonthyeartotal_payments 列。而且我必须根据来计算total_payments

如何计算值?

我在想这样的代码:

select 
month, year, sum(total_payments)
from
webassignment.subscription_stats
group by
day;

select
month, year, sum(total_payments)
from
webassignment.subscription_stats
group by
month;

select
month, year, sum(total_payments)
from
webassignment.subscription_stats
group by
year;

但它不会返回正确答案。我想按天、按月、按年计算 total_payments。请帮我找到值(value)。

示例输入:

Day Month   Year    Total_payments
10 01 2008 10
10 01 2008 20
11 02 2008 10
10 03 2010 10

输出:

日间:

day month year total_payments
-----------------------------
10 01 2008 30
11 02 2008 10
10 03 2010 10

同月同年

最佳答案

您可以使用 GROUP BY WITH ROLLUP 获得按年、月和日汇总的汇总:

SELECT
`Year`,
`Month`,
`Day`,
SUM(`Total_payments`) as `Totals`
FROM `webassignment`.`subscription_stats`
GROUP BY `Year`,`Month`,`Day` WITH ROLLUP;

如果你想单独查询年、月、日:

按年份:

SELECT
`Year`,
SUM(`Total_payments`) as `Totals`
FROM `webassignment`.`subscription_stats`
GROUP BY `Year`
ORDER BY `Year;

按月:

SELECT
`Year`,
`Month`,
SUM(`Total_payments`) as `Totals`
FROM `webassignment`.`subscription_stats`
WHERE `Year` = 2017
GROUP BY `Year`,`Month`
ORDER BY `Year`,`Month`;

按天:

SELECT
`Year`,
`Month`,
`Day`,
SUM(`Total_payments`) as `Totals`
FROM `webassignment`.`subscription_stats`
GROUP BY `Year`,`Month`,`Day`
ORDER BY `Year`,`Month`,`Day`;

关于Mysql根据条件计算列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44105673/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com