这让我很困惑......
如果我有一个 MySQL 表:
UserId | Commission | Date Of Commission
1 | 200.00 | 2014-02-12
1 | 50.00 | 2014-04-01
2 | 10.00 | 2014-04-05
我想显示特定用户从他/她的第一条记录开始每周的总佣金,如果没有记录,则显示该范围的 0。
我该怎么做?
示例输出
UserId | Date Range | Total Commission
1 | 02/10/14 - 02/16/14 | 200.00
1 | 02/17/14 - 02/23/14 | 0.00
...
1 | 03/31/14 - 04/06/14 | 50.00
我不是一位经验丰富的编码员,因此我们将不胜感激任何帮助。
谢谢!
编辑:
我已经尝试过这个:
SELECT IFNULL(SUM(Commisssion),0) Total ,DATE_SUB(`DateOfCommission`,INTERVAL 7 DAY)
AS RangStart,DATE_SUB(`DateOfCommission`,INTERVAL 1 DAY) AS RangeEnd
FROM `comms` WHERE `UserId` = '$UserID' GROUP BY DATE(`DateOfCommission`) DESC
但它从输入第一条记录的日期开始一周..
最佳答案
这很难实现。这是我通过一些小的修改设法做到的,它应该按需要的方式工作。我已经为 userid = 1 完成了此操作,也可以为其他用户完成此操作。
在查询中我有 2 行
where a.Date BETWEEN (select min(date) from transactions where UserId = 1) AND NOW()
和
WHERE date BETWEEN (select min(date) from transactions where UserId = 1) AND NOW()
查询将尝试使用用户截至今天的交易 min() 日期生成日期列表。这也可以用作用户的 max() 交易日期,而不是 now()。
select
t1.date_range,
coalesce(SUM(t1.Commission+t2.Commission), 0) AS Commission
from
(
select
a.Date as date,
concat(
DATE_ADD(a.Date, INTERVAL(1-DAYOFWEEK(a.Date)) +1 DAY),
' - ',
DATE_ADD(a.Date, INTERVAL(7- DAYOFWEEK(a.Date)) +1 DAY)
) as date_range,
'0' as Commission
from (
select curdate() - INTERVAL (a.a + (10 * b.a) + (100 * c.a)) DAY as date
from (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as a
cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as b
cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as c
) a
where a.Date BETWEEN (select min(date) from transactions where UserId = 1) AND NOW()
)t1
left join
(
SELECT date ,
coalesce(SUM(Commission), 0) AS Commission
FROM transactions
WHERE date BETWEEN (select min(date) from transactions where UserId = 1) AND NOW()
AND UserId = 1
GROUP BY date
)t2
on t2.date = t1.date
group by t1.date_range
order by t1.date_range asc
<强> DEMO
关于php - MySQL + PHP : Display items per week?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23868287/