Sql 计算两列的差值,并在另一列中输出结果

Sql 计算两列的差值,并在另一列中输出结果,sql,sql-server,lag,difference,Sql,Sql Server,Lag,Difference,目标-尝试根据两个标准(行数和个人ID)计算月份之间的差异 我不知道怎样才能得到不同 应根据人员ID和行号计算月差 行数越大,表示月值最大 这是数据 当前数据 结果 我认为lag()可以满足您的需求: select rownum, personid, month, (month - lag(month) over (partition by personid order by month) ) as diff from t; 请注意,对于第一行,d

目标-尝试根据两个标准(行数和个人ID)计算月份之间的差异

我不知道怎样才能得到不同

应根据人员ID和行号计算月差

行数越大,表示月值最大

这是数据

当前数据

结果

我认为
lag()
可以满足您的需求:

select rownum, personid, month,
       (month -
        lag(month) over (partition by personid order by month)
       ) as diff
from t;
请注意,对于第一行,
diff
将是
NULL
,而不是
“第一次”


你可以试一试。

我不想在这里抢戈登的风头,因为他做了最难的部分

下面是将NULL转换为“First Time”的额外步骤

create table #pivottabledata(Rownum int, PersonId int, Month int);
insert into #pivottabledata values(1,123,1);
insert into #pivottabledata values(2,123,2);
insert into #pivottabledata values(3,123,4);
insert into #pivottabledata values(4,123,5);
insert into #pivottabledata values(5,123,12);
insert into #pivottabledata values(1,222,1);
insert into #pivottabledata values(2,222,3);
insert into #pivottabledata values(3,222,4);
select * from #pivottabledata;
with cte (rownum,personid,month,diff) AS
(
select rownum, personid, month,
       (month -
        lag(month) over (partition by personid order by month)
       ) as diff
from #pivottabledata
)
SELECT rownum personid, month, 
       ISNULL(CAST(diff AS VARCHAR(max)), 'First Time') as diff
from cte;

请更新您的问题,并在描述中添加数据库模式、数据、您尝试过的查询和预期结果。请参阅:您应该将数据作为文本而不是图像发布。这里的结果图像是什么?这就是你想要的输出吗?Als@SeanLange-op需要更多的分数才能做到这一点。我是为他做的。此外,您的数据中始终会有连续的月份。第1、3和4个月-你会怎么做-第3个月和第1个月之间的差异是无效的。我已经添加了这个供其他人使用。比图片效果更好…真的很好的答案。在那里学到了一些新东西。还为SQL添加了一个链接。所以OP可以运行它来查看它是否正确。感谢您的帮助和建议。我对堆栈溢出很陌生。不完全确定哪些信息有用,哪些不有用。