伙计我有两个名为Requisition
和RequisitionHistory
的表。表Requisition
是唯一条目,其中唯一条目基于RequisitionCode
(PK),但表RequisitionHistory
中有多行基于RequisitionCode
因为每次都有Requisition
在RequisitionHistory
表上执行任何操作(例如更新等),在Requisiton
中插入新条目。
这是我的+-----------------+---------------+--------------------+
| RequisitionCode | ApprovedCount | RequisitionDate |
+-----------------+---------------+--------------------+
| 1 | 10 | 02/01/2014 |
| 2 | 23 | 01/01/2014 |
| 3 | 3 | 02/01/2014 |
+-----------------+---------------+--------------------+
表
RequisitionHistory
这是我的+------------------------+-----------------+---------------+-----------------+
| RequisitionHistoryCode | RequisitionCode | ApprovedCount | RequisitionDate |
+------------------------+-----------------+---------------+-----------------+
| 1 | 1 | 14 | 01/01/2014 |
| 2 | 1 | 10 | 02/01/2014 |
| 3 | 2 | 23 | 01/01/2014 |
| 4 | 3 | 1 | 01/01/2014 |
| 5 | 3 | 3 | 02/01/2014 |
+------------------------+-----------------+---------------+-----------------+
表
RequisitionDate
这些表中还有其他列,但是对于我的查询,它们是无关的,因此它们不包括在内。
现在我要做的是从ApprovedCount
获取每个RequisitionCode
的最新信息(基于RequisitionHistory
)ApprovedCount
,然后从RequisitionCode
中删除它相同RequisitionCode
的第二个最后一个条目(RequisitionHistory
中select RequisitionCode ,
(ISNULL((select top 1 ApprovedCount from RequisitionHistory
where RequisitionCode =r.RequisitionCode order by RequisitionDate desc),0)
-
ISNULL(
(select top 1 ApprovedCount from RequisitionHistory where RequisitionCode
NOT IN
(select top 1 ApprovedCount from RequisitionHistory
where RequisitionCode =r.RequisitionCode order by RequisitionDate desc)
and RequisitionCode = r.RequisitionCode order by RequisitionDate DESC),0))
as StructureChange from Requisition r
可能有一个或多个条目
我试图做什么(但悲惨地失败)
{{1}}
我做错了什么?
答案 0 :(得分:0)
尝试此操作后会得到什么:
select RequisitionCode ,
(
ISNULL((select top 1 ApprovedCount from RequisitionHistory rh
where rh.RequisitionCode =r.RequisitionCode order by rh.RequisitionDate desc),0)
-
ISNULL(
(select top 1 ApprovedCount from RequisitionHistory rh1 where rh1.RequisitionHistoryCode
NOT IN
(select top 1 RequisitionHistoryCode from RequisitionHistory rh2
where rh2.RequisitionCode =r.RequisitionCode order by rh2.RequisitionDate desc)
and rh1.RequisitionCode = r.RequisitionCode order by rh1.RequisitionDate DESC),0))
as StructureChange
from Requisition r
答案 1 :(得分:0)
在Sql Server中,您可以用稍微更易读的方式来完成它:
WITH AprovalRecency AS (
SELECT RequisitionCode, ApprovedCount,
RANK () OVER (PARTITION BY RequisitionCode
ORDER BY RequisitionHistoryCode DESC) as Recency
FROM RequisitionHistory
WHERE)
SELECT r.*, COALESCE(ar2.ApprovedCount, 0) - COALESCE(ar1.ApprovedCount, 0)
FROM Requisition r LEFT JOIN
AprovalRecency ar1 ON r.RequisitionCode = ar1.RequisitionCode
AND ar1.Recency = 1 LEFT JOIN
AprovalRecency ar2 ON r.RequisitionCode = ar2.RequisitionCode
AND ar2.Recency = 2