1

根据下图,我有以下 MySQL 表。该表名为 example_table: 示例表定义

该表包含已售出的产品列表、售出时间以及售价。

现在,我试图在表格上进行一些“分析”,以确定用户输入的特定日期前 5 天的平均销售价格。

我试图实现的输出如下。 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

此查询给出以下结果,但请注意缺少的天数。

尝试查询的 SQL 结果

IE 5 月 16 日和 5 月 17 日没有销售数据,我需要根据上面的预期结果图像在结果中显示这一点。

4

2 回答 2

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 |
于 2013-05-22T06:47:47.410 回答
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)
于 2013-05-22T19:17:56.817 回答