GROUP BY 后数据查询疑问请教?

m0_38033608 2018-06-02 08:51:07
有一个表有,(物品),(数量),(时间),三个字段
如何通过group by (物品)后,找到最新和最旧的(时间),计算出最新和最旧的(时间)对应的(数量)的差值
不通过存储过程能否实现?
...全文
882 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
二月十六 2018-06-02
  • 打赏
  • 举报
回复
借1#版主数据
use tempdb
go
if OBJECT_ID('t') is not null drop table t
go
create table t(
goods nvarchar(20),
num int,
theTime datetime
)
go
insert into t values('桌子',5,'2018-01-01')
insert into t values('桌子',25,'2018-01-31')
insert into t values('桌子',15,'2018-02-01')
insert into t values('椅子',20,'2018-02-03')
insert into t values('椅子',40,'2018-02-05')
GO
;WITH cte AS(
SELECT *,
ROW_NUMBER() OVER (PARTITION BY goods ORDER BY theTime) rn1,
ROW_NUMBER() OVER (PARTITION BY goods ORDER BY theTime DESC) rn2
FROM t
)
SELECT a.goods,
b.num - a.num AS 差值
FROM cte a
JOIN cte b
ON b.goods = a.goods
WHERE b.rn2 = 1
AND a.rn1 = 1;


吉普赛的歌 2018-06-02
  • 打赏
  • 举报
回复
use tempdb
go
if OBJECT_ID('t') is not null drop table t
go
create table t(
goods nvarchar(20),
num int,
theTime datetime
)
go
insert into t values('桌子',5,'2018-01-01')
insert into t values('桌子',25,'2018-01-31')
insert into t values('桌子',15,'2018-02-01')
insert into t values('椅子',20,'2018-02-03')
insert into t values('椅子',40,'2018-02-05')
go
;with cte as(
select goods,max(theTime) as maxTime,min(theTime) as minTime from t group by goods
)
select
*
,(select top 1 t.num from t where t.theTime=cte.maxTime) as maxTimeNum
,(select top 1 t.num from t where t.theTime=cte.minTime) as minTimeNum
,(select top 1 t.num from t where t.theTime=cte.maxTime)
-
(select top 1 t.num from t where t.theTime=cte.minTime) as subNum
from cte

27,579

社区成员

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

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