确定带时间戳记录的月度值

时间:2010-11-03 19:21:22

标签: sql mysql datetime

我有一个包含以下架构的SQL表:

fruit_id INT 
price    FLOAT
date     DATETIME

此表包含许多记录,其中给定水果的价格在给定时间记录。一天内可能有多条记录,可能有

我希望能够获取过去12个月(包括当月)单个水果的价格清单。所以给出fruit_id为2和datetime of now(),12月,1月,2月,10月,11月的价格值是多少?

鉴于上述要求,您将使用什么策略来获取此数据?纯sql,获取所有价格和代码处理?

谢谢你的时间。

3 个答案:

答案 0 :(得分:2)

您在谈论最低价格,最高价格,平均价格还是其他什么?

这是一个快速查询,帮助您入门,其中包括fruit_id 2的每月最低,最高和平均价格:

select left(date,7) as the_month, min(price),max(price),avg(price)
from fruit_price
where fruit_id = 2
and date >= concat(left(date_sub(curdate(), interval 11 month),7),'-01')
group by the_month;

答案 1 :(得分:1)

如果我从 -

正确理解

I would like to be able to fetch a list of prices for a single fruit over the last 12 months inclusive of the current month. So given a fruit_id of 2 and datetime of now(), what would the price values be for December, January, February, ... October, November?

根据您传递的日期和fruit_if,您需要一年中每个月的总价格。

所以,这不会给出一年中的所有月份,而是所有月份都有一年的价格。如果你想要所有月份......你需要创建一个dimdate表,它将包含所有日期..然后加入它..

    declare @passeddate=Now() --date to be calculated
    declare @fruit_id=2 --fruit id to be calculated
    Select 
          fruit_id as FruitId,
          Sum(price) as MonthPrice,
          Month(date)  as FruitMonth
    from SQL_Table 
    group by FruitMonth,FruitId  
    where fruit_id=@fruit_id and
    Year(date)=Year(@passeddate)

答案 2 :(得分:0)

select month(date) as "Month", distinct(price) as "Unique Price" where fruit_id = 2 group by month(date);

我尝试在SQL中尽可能多地声明不需要对数据进行无索引访问,因为它通常比使用应用程序处理数据快(呃)。

相关问题