数据库时间求环比问题

xxq9900 2010-04-01 05:37:15
有一个按天记录产品销售量的表,字段主要有(id,日期,销售量),现在想获得产品的周或者月的环比增长,该如何做,请高手指教,谢谢!
...全文
113 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
xxq9900 2010-04-12
  • 打赏
  • 举报
回复
终于搞明白了,谢谢
xman_78tom 2010-04-02
  • 打赏
  • 举报
回复

-- 先根据原表统计每种产品,每个月的总销量
;with t as(
select id, datepart(mm,日期) [month], sum(销售量) [sales] from tab group by id, datepart(mm,日期)
)
-- 再将上月的总销量与本月的总销量进行关联,计算出本月相对于上月的增长
select t2.id, t2.[month], cast((t2.[sales]-t1.[sales])*100.0/t2.[sales] as number(10,2))
from t t1 inner join t t2
on t1.id=t2.id and t2.[month]-t1.[month]=1;

-- 没有数据,只能大概写一些了。
xxq9900 2010-04-02
  • 打赏
  • 举报
回复
2楼的代码看不懂,我是新手,能不能给写解释
幸运的意外 2010-04-01
  • 打赏
  • 举报
回复
楼主举个例子看看吧.什么事环对比呀?
xman_78tom 2010-04-01
  • 打赏
  • 举报
回复

-- 月环比增长(id 为产品 id)。
-- 周统计用 datepart(ww,日期)。当然这些数据都应该是同一年的。
;with t as(
select id, datepart(mm,日期) [month], sum(销售量) [sales] from tab group by id, datepart(mm,日期)
)
select t2.id, t2.[month], cast((t2.[sales]-t1.[sales])*100.0/t2.[sales] as number(10,2))
from t t1 inner join t t2
on t1.id=t2.id and t2.[month]-t1.[month]=1;

htl258_Tony 2010-04-01
  • 打赏
  • 举报
回复
TEST DATA

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧