[英]Mysql count columns values based on condition
我有一个表格,列有day
, month
, year
, total_payments
。 我必须根据days
, months
, years
计算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
daywise,monthwise,yearwise。 请帮我找到价值观。
样本输入:
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
月份和年份相同
一种方法可以是在联盟上使用,以显示基于不同逐级的不同结果
select day, month,year,sum(total_payments)
from webassignment.subscription_stats group by day, month,year
union
select null, month,year,sum(total_payments)
from webassignment.subscription_stats group by month,year
union
select null, null ,year,sum(total_payments)
from webassignment.subscription_stats group by year
order by year, month, day
你提供的样本应该足够了
select day, month,year,sum(total_payments)
from webassignment.subscription_stats group by day, month,year
order by day, month,year
您可以使用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`;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.