我一直在努力解决我目前遇到的这个问题。我们有一个包含id
,productid
,userid
,count
和downloaddate
的表格。下面的内容可以理解结构和结果。
+----+-----------+--------+-------+---------------+
| id | productid | userid | count | downloaddate |
+----+-----------+--------+-------+---------------+
| 1 | 9 | 231 | 2 | October 2017 |
| 2 | 8 | 230 | 1 | October 2017 |
| 3 | 9 | 287 | 1 | October 2017 |
| 4 | 9 | 200 | 2 | November 2017 |
+----+-----------+--------+-------+---------------+
所以我要循环的是获取所有productid
并返回count
列中记录的给定月份的downloaddate
总数。
要归还:
+------------+-------+---------------+
| productid | count | downloaddate |
+------------+-------+---------------+
| 9 | 3 | October 2017 |
| 8 | 1 | October 2017 |
| 9 | 2 | November 2017 |
+------------+-------+---------------+
有可能这样做吗?我已经尝试了这个,但它返回了count
productid
$sum = array();
$emparray = array();
foreach ($downloads as $download){
$emparray[] = $download;
}
foreach ($emparray as $downloaded){
if (!isset($sum[$downloaded->id])) {
$sum[$downloaded->id]['count'] = $downloaded->count;
$sum[$downloaded->id]['downloaddate'] = $downloaded->downloaddate;
} else {
$sum[$downloaded->id]['count'] += $downloaded->count;
$sum[$downloaded->id]['downloaddate'] = $downloaded->downloaddate;
}
}
任何帮助将不胜感激!
修改
这是我的SQL查询:
$downloads = $wpdb->get_results(
"
SELECT ast.*, dl.userid, dl.count, dl.downloaddate
FROM $lead_table as ast
JOIN $table_downloads as dl ON (dl.productid = ast.id)
"
);
答案 0 :(得分:1)
我认为你应该将你的sql Query编辑成:
deleteRows()
答案 1 :(得分:1)
你可以通过productid和downloaddate进行一次查询分组得到结果(我希望October2017
是问题中的拼写错误)
SELECT productid, sum(count) as count, downloaddate
FROM your_table
GROUP BY productid, downloaddate
更新。您的查询似乎是
SELECT ast.*, dl.userid, sum(dl.count) as count, dl.downloaddate
FROM $lead_table as ast
JOIN $table_downloads as dl
ON (dl.productid = ast.id)
GROUP BY dl.userid, dl.downloaddate
答案 2 :(得分:0)
你必须能够告诉downloaddate中给出了哪个月(你可以建立一个时间戳吗?或者其他一些东西告诉你" October2017"与#34; 2017年10月&#相同34。
一旦你得到了,你只是"只是"必须存储你的"总和"在2D数组中使用类似的东西:
$sum = array();
foreach ($downloads as $download) {
// dateToTimeStamp: custom function who gives you the same number for October2017 or October 2017
$timestamp = dateToTimeStamp($downloaded->downloaddate);
if (!isset($sum[$timestamp])) {
$sum[$timestamp] = [];
}
if (!isset($sum[$timestamp][$downloaded->id])) {
$sum[$timestamp][$downloaded->id]['count'] = $downloaded->count;
$sum[$timestamp][$downloaded->id]['downloaddate'] = $downloaded->downloaddate;
continue 1;
}
$sum[$timestamp][$downloaded->id]['count'] += $downloaded->count;
$sum[$timestamp][$downloaded->id]['downloaddate'] = $downloaded->downloaddate;
}
答案 3 :(得分:0)
您可以轻松使用此查询并从php中提取数据并在那里使用
select productid,sum(count),downloaddate from tablename group by productid,downloaddate