我想显示数据库产品组的平均价格。因此,我希望随时间推回该产品组中所有产品的平均价格。
首先,我想知道该组有多少价格变动。此查询使用此查询成功返回所有日期...
SELECT DISTINCT(DATE(gbp.prdate)) as dte
FROM sku AS s
INNER JOIN mt_price gbp ON s.id = gbp.
WHERE (gbp.prdate < NOW() - INTERVAL ? DAY) AND (s.grp = ?)`
然后我在php中使用foreach生成以下查询...
$i = 1;
$qry = "SELECT s.id AS sid, s.sku, s.title AS s_title,";
foreach ($dates as $date) {
$qry .= "(SELECT price FROM price WHERE price.sid = s.id AND prdate <= DATE(?) ORDER BY prdate LIMIT 1) AS ?, ";
$datearr[] = $date;
}
$qry = substr($qry, 0, -2) . " ";
$qry .= "FROM sku AS s
WHERE (s.grp = ?)
GROUP BY s.id
ORDER BY s.id";
$results = $db->prepare($qry);
foreach($datearr as $darr) {
$results->bindParam($i++,$darr->dte,PDO::PARAM_STR);
$results->bindParam($i++,$darr->dte,PDO::PARAM_STR);
}
上面的一个例子给了我这个查询...
SELECT s.id AS sid, s.rid, s.sku, s.title AS s_title,
(SELECT price FROM price WHERE price.sid = s.id AND prdate <= DATE('2015-01-08') ORDER BY prdate LIMIT 1) AS '2015-01-08',
(SELECT price FROM price WHERE price.sid = s.id AND prdate <= DATE('2015-02-12') ORDER BY prdate LIMIT 1) AS '2015-02-12',
(SELECT price FROM price WHERE price.sid = s.id AND prdate <= DATE('2015-01-26') ORDER BY prdate LIMIT 1) AS '2015-01-26',
(SELECT price FROM price WHERE price.sid = s.id AND prdate <= DATE('2015-02-08') ORDER BY prdate LIMIT 1) AS '2015-02-08',
(SELECT price FROM price WHERE price.sid = s.id AND prdate <= DATE('2015-01-30') ORDER BY prdate LIMIT 1) AS '2015-01-30',
(SELECT price FROM price WHERE price.sid = s.id AND prdate <= DATE('2015-02-02') ORDER BY prdate LIMIT 1) AS '2015-02-02'
来自sku AS 在哪里(s.cat =&#39; TLPT01&#39;) GROUP BY s.id. ORDER BY s.id
当我按上述方式运行此查询时,我得到了我期望的结果,每个SKU只有一个价格(低至LIMIT
)以及正确的价格。然后,当DATE
更改时,它会正确显示SKU的价格。我也好!
所以,我想要的是获得所有这些结果的平均值。如果我在AVG
前面使用s.id
,我会获得SKU的平均值,这显然不是任何结果。我想要返回的所有SKU的平均价格(因此,GROUP BY
应该只给我一行信息)。当我将GROUP BY
放在子查询之前时,我只是得到一个错误。
答案 0 :(得分:0)
你没有编码你所说的话; 每个日期的平均值。对子查询使用avg查询(简化):
select date, avg(avg_price) from (
select group_id, date, avg(price) avg_price
from mytable
group by group_id, date
) x
group by date
内部查询将为每个group_ id和date生成一个avg值,外部查询仅按日期平均那些group_id / date值。
答案 1 :(得分:0)
尝试按如下方式创建子查询 (SELECT AVG(price)FROM price WHERE price.sid = s.id AND prdate&lt; = DATE(?)GROUP BY price.sid)
答案 2 :(得分:0)
我发现将子查询移动到LEFT JOIN
解决方案中。然后,我可以对这些JOIN返回的价格进行AVG
。我仍然不知道为什么我不能只是AVG
子查询,但这种方法(虽然不是超级快)...工作。
SELECT s.cat, s.id AS sid, s.rid, s.sku, s.title AS s_title, AVG(pr1.price)
FROM sku AS s
LEFT JOIN (SELECT sid, price, prdate FROM price WHERE prdate <= DATE('2014-12-21') ) AS pr1 ON s.id = pr1.sid
... <more from foreach, add more AVG on top line> ...
WHERE (s.cat = 'TLPT01')
GROUP BY cat