use*_*575 6 sql lead sql-server-2012
我需要一些指导并帮助解决一个问题我不完全确定如何在SQL Server 2012中解决.我认为LAG和LEAD功能可能有用,但我不确定.
这就是我现在的数据:
=========================================
YearMonth LocationCode Active
=========================================
201405 123 0
201406 123 2
201409 211 1
201410 211 0
201411 214 0
201412 214 3
Run Code Online (Sandbox Code Playgroud)
我们有一个YearMonth列显示每个状态的状态,locationCode以及Active表示每个状态的int 的列LocationCode
目的:
我的目标是比较LocationCode当前YearMonth(让我们称之为201406)和前一个Yearmonth(让我们称之为201405)的for :
一个例子 :
=========================================
YearMonth LocationCode Active
=========================================
201405 123 0
201406 123 2
Run Code Online (Sandbox Code Playgroud)
基本上我想弄清楚的是如何将当前月份的行(201406)与上一个月的行(201405)进行比较Active.
如果当前月份的行列Active为非零且前一个月的活动为零,则我们将当前月份的行结束为"新"(1)否则为(0).
下面提供了一个示例:
==================================================
YearMonth LocationCode Active New
===================================================
201405 123 0 0
201406 123 2 1
201409 211 1 0
201410 211 0 0
201411 214 0 0
201412 214 3 1
Run Code Online (Sandbox Code Playgroud)
我怎么解决这个问题?
我认为你可以使用这样的查询:
SELECT *,
CASE
WHEN Active <> 0 AND
ISNULL(LAG(Active) OVER (PARTITION BY LocationCode ORDER BY YearMonth), 0) = 0 THEN 1
ELSE 0
END As New
FROM yourTable;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3001 次 |
| 最近记录: |