我想在我的sql语句中创建一个新列,如果MRN和TF_Group被重复但PathID不同(请参见下面显示我的输出的链接),则该标志的标记为“是”
我已经能够在excel中创建该列(请参阅下面的链接,尤其是标题为“ Flag”的列),但只是想不出如何在sql server中复制它。我用来创建“标志”列的函数是= if(and(b2 = b3,d2 = d3,a2 <> a3),“是”,“否”)
我只是不知道如何在sql server中重新创建类似的东西。下面是我用来提取数据的sql代码,您可以在本文底部的链接中看到该数据。
有人有什么主意吗?
select DISTINCT
[Pathway ID] PathID,
MRN,
DENSE_RANK() OVER(PARTITION BY mrn ORDER BY [Pathway ID]) RK,
[Treatment Function Group] TF_GROUP,
'' [Flag]
from [HRS_RTT].[dbo].[tbl_PMM_IncompletePTL_CG_Snapshot]
where convert(date,censusdate) between '03-jun-19' and '09-jun-19'
AND MRN IS NOT NULL
AND [Treatment Function Group] IS NOT NULL
order by
MRN,
[Pathway ID]
答案 0 :(得分:1)
如评论中所建议:
select DISTINCT
[Pathway ID] PathID,
MRN,
CASE WHEN MRN = MRN AND [Treatment Function Group] = [Treatment Function Group] AND [Pathway ID] <> [Pathway ID] THEN 'YES' ELSE 'NO' END [Flag]
from [HRS_RTT].[dbo].[tbl_PMM_IncompletePTL_CG_Snapshot]
where convert(date,censusdate) between '03-jun-19' and '09-jun-19'
AND MRN IS NOT NULL
AND [Treatment Function Group] IS NOT NULL
order by
MRN,
[Pathway ID]
答案 1 :(得分:1)
这里是您所描述问题的解决方案。它使用T-SQL LEAD
函数在各行之间进行比较。请注意,由于您不清楚要执行的操作尚不清楚,因此我没有在原始查询中包含DISTINCT
条条件。
但是,正如我在评论中说的那样,我认为这不一定是您要执行的操作。您可能需要进一步考虑自己的要求,看看是否可以提出一种更好的方法来满足要求。
select
PathID,
MRN,
TF_Group,
case
when MRN = Next_MRN and TF_Group = Next_TF_Group and PathID <> Next_PathID then 'Yes'
else 'No'
end as Flag
from (
select
[Pathway Id] as PathID,
MRN,
[Treatment Function Group] as TF_Group,
lead([Pathway Id]) over (order by MRN, [Pathway ID]) as Next_PathID,
lead(MRN) over (order by MRN, [Pathway ID]) as Next_MRN,
lead([Treatment Function Group]) over (order by MRN, [Pathway ID]) as Next_TF_Group
from tbl_PMM_IncompletePTL_CG_Snapshot
) x
order by MRN, PathID