我有两个表,一个是“complete_bets”,另一个是“用户”。在第一个表格中,我有一个列利润,用户可以逐日输入他们的损益,这是表截图:
用户表有一个列'user_registered',我们在其中存储了用户注册的日期。
我想在几周内获得任何用户的利润,意味着作为网站会员的周数获利。
现在我正在使用此查询:
SELECT CONCAT(YEAR(`date_added`), '/', WEEK(`date_added`)) AS lol,
WEEK(`date_added`) AS week_name, SUM(profit) as overallProfit
FROM wpdw_complete_bets
WHERE user_id = '1'
GROUP BY week_name
ORDER BY date_added ASC
但它让我在一年中获得了一个星期,但我希望每周的盈利/亏损与网站上的会员周数一致。
我想要那样的结果
userId no_of_week_user_register profit
1 1 100
1 2 120
1 4 150
no_of_week_user_register就像第一周注册后用户在第二周获得100个配置文件时获得120个,在第4周形成注册时获得150个。
请告诉我如何编写查询以使其正常工作,任何形式的帮助都会非常明显。
答案 0 :(得分:0)
也许是这样的:
SELECT YEARWEEK(`date_added`) AS week_name,
SUM(IF(profit > 0, profit, 0)) as profit,
SUM(IF(profit < 0, profit, 0)) as loss
FROM wpdw_complete_bets
WHERE user_id = 1
GROUP BY week_name
ORDER BY week_name ASC
编辑: 那么你想要用户注册后的周数?
SELECT TIMESTAMPDIFF(WEEK, ?user_create_date, `date_added`) AS week_name,
SUM(IF(profit > 0, profit, 0)) as profit,
SUM(IF(profit < 0, profit, 0)) as loss
FROM wpdw_complete_bets
WHERE user_id = 1
GROUP BY week_name
ORDER BY week_name ASC