如果我有桌面日志:
ID Date P_id TYPE
-------------------------------
1 2016-9-1 11 adClick
2 2016-9-1 22 adComplete
3 2016-9-1 11 adClick
4 2016-9-3 22 adClick
5 2016-9-3 22 adClick
6 2016-9-1 11 adClick
7 2016-9-3 22 adComplete
8 2016-9-1 11 adClick
9 2016-9-3 11 adClick
-------------------------------
和另一个具有相同日期& P_id如下:
ID Date P_id clicks
--------------------------------
1 2016-9-1 11
2 2016-9-3 11
3 2016-9-1 11
4 2016-9-3 11
5 2016-9-1 22
6 2016-9-1 11
5 2016-9-1 22
---------------------------------
我需要MySQL查询根据键(日期和时间P_id)在报告表中传播点击次数,如果有余数,则添加一个随机的直到完成余数并选择相同的键:
clicks =
count of rows having (Date & P_id) in logs table
------------------- Divistion (/) -------------------
count of rows having (Date & P_id) in Report and Type is adClick
按键(日期& P_id)和事件类型的每个组的计数是日志表中的adClick:
2016-9-1 11 --- count--> 4
2016-9-1 22 --- count--> 0
2016-9-3 11 --- count--> 1
2016-9-3 22 --- count--> 2
并在报告表中计算:
2016-9-1 11 --- count--> 3
2016-9-1 22 --- count--> 2
2016-9-3 11 --- count--> 2
2016-9-3 22 --- count--> 0
所以表格将是:
ID Date P_id clicks
--------------------------------
1 2016-9-1 11 4 / 3 = 1 and 1 as remainder
2 2016-9-3 11 1 / 2 = 0 and 1 as remainder
3 2016-9-1 11 4 / 3 = 1 and 1 as remainder
4 2016-9-3 11 1 / 2 = 0 and 1 as remainder
5 2016-9-1 22 0 / 2 = 0
6 2016-9-1 11 4 / 3 = 1 and 1 as remainder
5 2016-9-1 22 0 / 2 = 0
---------------------------------
示例解释更多,第一行:
2016-9-1 11 4 / 3
4 rows (2016-9-1 11) in logs table with type=adClick by
3 row (2016-9-1 11) in report table
我已经完成了保存点击而没有余下的部分,因此在报告表中使用我的查询的记录是:
ID Date P_id clicks
--------------------------------
1 2016-9-1 11 1
2 2016-9-3 11 0
3 2016-9-1 11 1
4 2016-9-3 11 0
5 2016-9-1 22 0
6 2016-9-1 11 1
5 2016-9-1 22 0
---------------------------------
现在我想将余数 - 可能是随机的 - 传播到报告表中,以便相同键的总和保持不变:
ID Date P_id clicks
--------------------------------
1 2016-9-1 11 1 + 1
2 2016-9-3 11 0 + 1
3 2016-9-1 11 1
4 2016-9-3 11 0
5 2016-9-1 22 0
6 2016-9-1 11 1
5 2016-9-1 22 0
---------------------------------
因此,对于两个表,现在(2016-9-1 11)的点击总和为4。
以下是我在使用余数之前用来更新的查询:
UPDATE report AS r
INNER JOIN
(
SELECT DATE(ctr_date) as report_date, report.placement_id, count(*) as cnt_report, cnt_event_type
FROM report
INNER JOIN
(
SELECT DATE(ctr_date) as event_date, placement_id, SUM(event_type = 'adClick') as cnt_event_type
FROM logs
GROUP BY DATE(ctr_date),placement_id
) inner_report
ON report.date = inner_report.event_date AND report.placement_id = inner_report.placement_id
GROUP BY report.date, report.placement_id
) result_table
ON r.date = result_table.report_date AND r.placement_id= result_table.placement_id
SET r.clicks = COALESCE( (cnt_event_type - MOD(cnt_event_type,cnt_report))/cnt_report ,0);
我正在考虑使用相同的查询,但对相同的密钥使用限制(余数)并使用:
SET r.clicks = r.clicks + 1
答案 0 :(得分:0)
我在临时表中保存了相同键的余数。并且使用该表遍历报告表中的相同密钥,并根据临时表中的余数值递增前一个值。