用于查找最近趋势项的SQL

时间:2012-02-23 22:47:16

标签: sql

我有一个包含以下数据列的表

date item

每一行都是在哪个日期购买的商品的交易记录。如何编写SQL以在两个时间范围内以百分比形式查找获得最多销售额的项目。例如,为了每天按项目销售一周,我可以做到

select
 date,
 item,
 count(*)
from table
date >= '2012-01-01'
date <= '2012-01-07'
group by 1,2 order by 1

如果我更改下周的日期范围,我可以获得该周售出的商品。 但我想找到一个SQL解决方案,无需在Excel中操作数据即可完成这项工作。

2 个答案:

答案 0 :(得分:0)

你试过这个吗?

select item
     , 100 * count(*) / ( select count(*) 
                            from table 
                           where date between '2012-01-01' and '2012-01-07'
                                 ) as avrg 
  from table 
 where date between '2012-01-01' and '2012-01-07' 
 group by item 
 order by item

答案 1 :(得分:0)

我第一次总是向后退,但下面的内容可能会让你开始。

SELECT d1.item, COUNT(d1.item) / COUNT(d2.item) AS slope
FROM data AS d1
JOIN data AS d2 ON d2.item = d1.item
WHERE d1.date > '2012-01-01'
AND d2.date > '2012-01-07'
GROUP BY d1.item
ORDER BY COUNT(d1.item) / COUNT(d2.item) DESC