我有以下MySQL表格,如下图所示。该表名为example_table:
该表包含已售出产品的清单,销售时间以及售价。
现在,我试图在桌面上进行一些“分析”,以确定在给定用户输入的特定输入日期的前5天中的销售平均销售价格。
我想要实现的输出如下:
我有部分查询,但这不完全符合我的要求。
SELECT product_name,time_value,AVG(selling_price) as 'Average Selling Price'
from example_table
where product_name='Samsung Galaxy S4'
and time_value in (
(SELECT SUBDATE('2013-05-21',INTERVAL 1 DAY)),
(SELECT SUBDATE('2013-05-21',INTERVAL 2 DAY)),
(SELECT SUBDATE('2013-05-21',INTERVAL 3 DAY)),
(SELECT SUBDATE('2013-05-21',INTERVAL 4 DAY)),
(SELECT SUBDATE('2013-05-21',INTERVAL 5 DAY)))
group by product_name,time_value
order by time_value asc
此查询提供以下结果但请注意缺少的日期。
I.E 5月16日和5月17日没有销售数据,我需要根据上面的预期结果图像显示结果。
答案 0 :(得分:1)
您可以这样做:
SELECT
d.date,
d.product_name,
COALESCE(AVG(selling_price), 0) as 'Average Selling Price'
from
(
SELECT 'Samsung Galaxy S4' AS Product_name,
SUBDATE('2013-05-21', INTERVAL 1 DAY) AS date
UNION ALL
SELECT 'Samsung Galaxy S4', SUBDATE('2013-05-21',INTERVAL 2 DAY)
UNION ALL
SELECT 'Samsung Galaxy S4', SUBDATE('2013-05-21',INTERVAL 3 DAY)
UNION ALL
SELECT 'Samsung Galaxy S4', SUBDATE('2013-05-21',INTERVAL 4 DAY)
UNION ALL
SELECT 'Samsung Galaxy S4', SUBDATE('2013-05-21',INTERVAL 5 DAY)
) AS d
LEFT JOIN
(
SELECT *
FROM example_table
WHERE product_name = 'Samsung Galaxy S4'
) AS e ON d.date = e.time_value
group by d.product_name, d.date
order by d.date asc;
请在此处查看:
这会给你:
| DATE | PRODUCT_NAME | AVERAGE SELLING PRICE |
----------------------------------------------------------
| 2013-05-16 | Samsung Galaxy S4 | 0 |
| 2013-05-17 | Samsung Galaxy S4 | 0 |
| 2013-05-18 | Samsung Galaxy S4 | 517.5 |
| 2013-05-19 | Samsung Galaxy S4 | 482.5 |
| 2013-05-20 | Samsung Galaxy S4 | 460 |
答案 1 :(得分:1)
检查SQLFIddle。
SELECT
@rn := @rn - 1 AS row_num,@am := DATE_SUB('2013-05-21', INTERVAL @rn DAY ) AS 'time_value',et.product_name,
IFNULL((SELECT
AVG(er.selling_price)
FROM
example_table er
WHERE
er.time_value = @am
GROUP BY @am ),0) AS 'Average Selling Price'
FROM
(SELECT @rn := 6 , @am := DATE_SUB('2013-05-21', INTERVAL @rn DAY) ) r ,
example_table et
WHERE et.product_name = "Samsung Galaxy S4" AND et.time_value > DATE_SUB('2013-05-21', INTERVAL 6 DAY)