寻找MySQL查询的最后一些帮助....我非常接近,但却无法弄清楚如何完成它!
我基本上试图计算每个客户每月的金额,我可以这样做,查询下面的代码:
select customer_id,
SUM(CASE WHEN month(payment_date)= 1 THEN amount ELSE 0 END) AS "Jan",
SUM(CASE WHEN month(payment_date)= 2 THEN amount ELSE 0 END) AS "Feb",
SUM(CASE WHEN month(payment_date)= 3 THEN amount ELSE 0 END) AS "March",
SUM(CASE WHEN month(payment_date)= 4 THEN amount ELSE 0 END) AS "April",
SUM(CASE WHEN month(payment_date)= 5 THEN amount ELSE 0 END) AS "May",
SUM(CASE WHEN month(payment_date)= 6 THEN amount ELSE 0 END) AS "June",
SUM(CASE WHEN month(payment_date)= 7 THEN amount ELSE 0 END) AS "July",
SUM(CASE WHEN month(payment_date)= 8 THEN amount ELSE 0 END) AS "Aug",
SUM(CASE WHEN month(payment_date)= 9 THEN amount ELSE 0 END) AS "Sept",
SUM(CASE WHEN month(payment_date)= 10 THEN amount ELSE 0 END) AS "Oct",
SUM(CASE WHEN month(payment_date)= 11 THEN amount ELSE 0 END) AS "Nov",
SUM(CASE WHEN month(payment_date)= 12 THEN amount ELSE 0 END) AS "Dec"
from payment
group by customer_id
Table Layout:
Table Name: payment
payment_id smallint(5)
customer_id smallint(5)
staff_id tinyint(3)
rental_id int(11)
amount decimal(5,2)
payment_date datetime
last_update timestamp
OUTPUT:
customer_id Jan Feb March April May June
1 0 0.99 3.98 **0** 4.51 0
Expected:
customer_id Jan Feb March April May June
1 0 0.99 **3.98** **3.98** 4.51 4.51
然而,我无法解决的问题是如果金额= 0,如果金额等于最后金额,即如果金额落入其他语句,它需要等于上个月的金额而不是零。如果上个月是0那么那很好,但是如果最后几个月的金额是> 1,则金额不能为0。 0
注意:已经从phpadmin演示服务器对MySQL sakila数据库进行了查询以进行测试。
非常感谢任何帮助或指导!
更新 - 按语句切断组,现在已添加到上面的代码中。 更新 - 代码块中包含的表结构。
答案 0 :(得分:0)
感谢大家的帮助。
我最终使用表示层(JavaScript),感谢@Strawberry,来执行值。