0
我有以下查询我想添加我的查询左加入与CTE如何做到这一点,请帮助我,因为我有驱动程序ID我想第二个最后的驱动程序ID,但我想添加左连接与CTE如何添加与CTE的左加入,检查我的查询
select d.Id,d.DriverNo,d.DriverName,TransId=dc.Id,dc.FromDate,dc.ToDate,dc.IsPaid,
Active=(case when (dc.weekoff is null or dc.weekoff=0) then 'Active' else 'Off' end),
Rent=(case when (IsNull(dc.CommissionTotal,0))> IsNull(dc.AccJobsTotal,0) then IsNull(dc.CommissionTotal,0)-(IsNull(dc.AccJobsTotal,0)) else 0 end),
BalanceDue=IsNull(dc.OldBalance,0),
AgentCommission=IsNull(dc.AgentFeesTotal,0),
PDA= (case when (dc.weekoff is null or dc.weekoff=0) then (IsNull(dc.PDARent,0)+IsNull(dc.CollectionDeliveryCharges,0)) else 0 end),
Total=(case when (IsNull(dc.CommissionTotal,0))> IsNull(dc.AccJobsTotal,0) then IsNull(dc.CommissionTotal,0)-(IsNull(dc.AccJobsTotal,0)) else 0 end)
+((IsNull(dc.OldBalance,0))
+((IsNull(dc.AgentFeesTotal,0)))
+(case when (dc.weekoff is null or dc.weekoff=0) then (IsNull(dc.PDARent,0)+IsNull(dc.CollectionDeliveryCharges,0)) else 0 end))
from Fleet_Driver d
inner join Fleet_DriverCommision dc
on d.Id=dc.DriverId
where dc.Id in (select Max(Id) from Fleet_DriverCommision
group by DriverId) as T1
left join on
> LEFT JOIN WITH CTE
With cte as
(select AgentFeesTotal,DriverId,Row_Number()over(Partition by DriverID order by Transdate desc) as Rn,
count(1)over(Partition by DriverID) as cnt from Fleet_DriverCommision)
Select AgentFeesTotal,DriverId
from cte
Where (Rn = 2 and cnt > 1) or (Rn = 1 and cnt = 1)
这是示例
与CTE 如 (选择AgentFeesTotal,DriverId,ROW_NUMBER()以上(分区由DriverID为了通过Transdate降序)用作Rn, 计数(1)在(由DriverID分区)作为来自Fleet_DriverCommision的cnt) 选择AgentFeesTo TAL,从CTE DriverId 凡(RN = 2和CNT> 1)或(RN = 1和CNT = 1)
选择t2.DriverNo从Fleet_Driver T2 左加入 CTEÇ 上c.DriverId = t2.Id
请提供一个最简单的工作示例。 – buhtz
与CTE 如 (选择AgentFeesTotal,DriverId,ROW_NUMBER()以上(分区由DriverID为了通过Transdate降序)用作Rn, 计数(1)在(由DriverID分区),如从Fleet_DriverCommision CNT) 选择AgentFeesTotal,DriverId 从CTE 凡(RN = 2和CNT> 1)或(RN = 1和CNT = 1) 选择t2.DriverNo从Fleet_Driver T2 左加入 CTEç 上c.DriverId = t2.Id –