【问题标题】:Query to return two columns from single field with mutually exclusive constraint查询以从具有互斥约束的单个字段返回两列
【发布时间】:2020-11-14 22:40:09
【问题描述】:

我想基本上从单个字段中显示两列;一个具有当前计划值,另一个具有下表结构的上一个计划。我只想选择 StatusId != 2 的记录(记录数=3)。并显示 StatusId = 2 的 PrevPlan 列。

想要一个像下面这样的输出。

已尝试查询

我使用了这些表的常规内部连接和外部应用(使用 CreatedDate Desc 进行排序,因为有更多旧值)来获取 PrevPlan。但它正在用相同的值更新整个 PrevPlan 列。返回记录数为3,正确。

    OUTER APPLY
        (
            SELECT TOP 1
                 PlanPrev.Id
                ,PlanPrev.[Name]                 
            FROM
                Plans PlanPrev
                inner join Trials tPrev on tPrev.PlanId = PlanPrev.Id
            WHERE
                tPrev.StatusId = 2
            ORDER BY
                tPrev.CreatedDate Desc
        ) AS PlanPrev

所以我在下面使用了一个 CTE,它正在更新,但它返回所有 6 条记录而不是 3 条。

WITH ContractsCTE (ContractId, CurrentPlan, PrevPlan)
AS
(
Select ContractId,  p.[Name] as CurrentPlan, p.[Name] as PrevPlan
from Trials t
inner join Contracts c on c.Id = t.ContractId
inner join Plans p on t.PlanId = p.Id
where  t.StatusId != 2
)
select ContractId,  cte.CurrentPlan, p.[Name] as PrevPlan
from ContractsCTE cte
left join Trials t1 on cte.ContractId = t1.ContractId
left join Contracts c1 on c1.Id = t1.ContractId
left join Plans p1 on t1.PlanId = p1.Id 
and t1.StatusId = 2 
Order by CreateDate desc;

有没有一种方法可以在不使用任何临时表/更新查询的情况下实现它?任何帮助将不胜感激。

【问题讨论】:

  • 对于contractid=3,最新的计划是7/19,但是显示为“current_plan”的计划是planid1
  • 这是一个错字。请忽略它。

标签: sql sql-server left-join inner-join common-table-expression


【解决方案1】:

我们可以先把之前的计划细节分开,然后再使用。

我稍微修改了 CTE 的第二部分如下:

select cte.ContractId,  cte.CurrentPlan, p1.[Name] as PrevPlan
from ContractsCTE cte
left join (SELECT t.CONTRACTID, t.STATUSID, t.PLANID, row_number() OVER (PARTITION BY t.CONTRACTID, t.STATUSID ORDER BY t.CREATEDATE DESC) rn FROM @TRAILS t WHERE t.STATUSID = 2)t1 
    on cte.ContractId = t1.ContractId AND t1.rn = 1
left join @CONTRACTS c1 on c1.Id = t1.ContractId AND t1.rn = 1
left join @PLANS p1 on t1.PlanId = p1.Id AND t1.rn = 1
Order by cte.CONTRACTID

db小提琴here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-27
    • 2019-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多