我有一张名为付款的表,它有日期字段,我有一个名为Mark的客户,他每天都在付款3年
Table: Payment
Fields: Name , Amountpaid, date
我希望每3个月显示一次支付记录,以及3年内支付的总金额
我希望结果如何
First 3 months payment record table
total Amountpaid at the bottom of the table
second 3 months payment record table
total Amountpaid at the bottom of the table
Third 3 months payment record table
total Amountpaid at the bottom of the table
等等3年
请帮忙
答案 0 :(得分:1)
您似乎正在为此寻找SQL解决方案,但数据库用于保存数据,而不是将其格式化为报表。为此我的建议是:不要尝试在数据库中执行此操作,而是在前端代码中执行此操作
运行像
这样的查询非常简单SELECT * FROM payment WHERE
name = 'mark' and
`date` between date_sub(now(), interval 3 year) and now()
ORDER BY date
然后将结果放入一个HTML表中,使用一个循环,以及一个跟踪付费总额的变量。每3个月重置一次变量。如果你想让MySQL做更多的数据处理来帮助你做到这一点:
SELECT * FROM
payment
INNER JOIN
(SELECT YEAR(`date`) + (QUARTER(`date`)/10) as qd, SUM(amountpaid) as qp FROM payment WHERE name = 'mark' GROUP BY YEAR(`date`), QUARTER(`date`)) qpt
ON
qpt.qd = YEAR(`date`) + (QUARTER(`date`)/10)
WHERE
name = 'mark' AND
`date` between date_sub(now(), interval 3 year) and now()
ORDER BY `date`
这将逐行提供所有商标的数据和额外的两列(大多数一遍又一遍地重复),显示一年中的年份和季度(3个月),如2017.1,2017.2,以及所有付款的总和在那个季度制作。现在在前端格式化它不需要变量来保持支付金额的累计总数
这是关于格式化数据库中数据(个人意见)应该做的限制。但是,如果您决定让MySQL完成所有这些,请继续阅读..
Ysth提到汇总,用于汇总数据..这样的解决方案看起来像这样:
SELECT
Name, `date`, SUM(amountpaid) as amountpaid
FROM
payment
WHERE
name = 'mark' AND
`date` between date_sub(now(), interval 3 year) and now()
GROUP BY
name,
YEAR(`date`) + (QUARTER(`date`)/10),
`date`
WITH ROLLUP
这种方法的唯一缺点是您还可以通过标记获得所有付款的总计行。要取消它,请改为使用分组集:
SELECT
Name, `date`, SUM(amountpaid) as amountpaid
FROM
payment
WHERE
name = 'mark' AND
`date` between date_sub(now(), interval 3 year) and now()
GROUP BY GROUPING SETS
(
(
name,
YEAR(`date`) + (QUARTER(`date`)/10),
`date`
),
(
name,
YEAR(`date`) + (QUARTER(`date`)/10)
)
)
答案 1 :(得分:1)
您可以使用年份和月份的分组乘以3并使用楼层截断
SELECT
EXTRACT(YEAR_MONTH FROM `date`),
SUM(`Amountpaid`)
FROM
`Payment`
WHERE
`Name` = 'Mark'
AND `date` >= DATE_SUB(NOW(), INTERVAL 3 YEAR)
GROUP BY
EXTRACT(YEAR FROM `date`),
FLOOR(EXTRACT(MONTH FROM `date`) / 3)
对于总数,您需要迭代结果集并总结已支付的金额,或者如果您希望它作为最终记录,您可以执行UNION SELECT
,但这样做会有效,但为了完整性,它是下面:
SELECT
EXTRACT(YEAR_MONTH FROM `date`),
SUM(`Amountpaid`)
FROM
`Payment`
WHERE
`Name` = 'Mark'
AND `date` >= DATE_SUB(NOW(), INTERVAL 3 YEAR)
GROUP BY
EXTRACT(YEAR FROM `date`),
FLOOR(EXTRACT(MONTH FROM `date`) / 3)
UNION SELECT
NULL,
SUM(`Amountpaid`)
FROM
`Payment`
WHERE
`Name` = 'Mark'
AND `date` >= DATE_SUB(NOW(), INTERVAL 3 YEAR)
答案 2 :(得分:0)
这是每3个月获得摘要:
select year(date)*100+floor(month(date)/3) as period, sum(amountpaid)
from payment
where name = 'mark' and (date between '2014-01-01' and '2017-01-01')
group by year(date)*100+floor(month(date)/3)
order by period
这是如何获得总结3年:
select sum(amountpaid) from payment where name = 'mark' and (date between '2014-01-01' and '2017-01-01')
您可以根据需要更改日期between