【发布时间】:2021-07-25 12:26:23
【问题描述】:
我想在CASE表达式的第二部分使用SNumber但不知道怎么用?
select
PE.EDateTime,
(case when(PE.EDateTime is not NULL and cast(PE.EDateTime as time) < '12:30') then cast(format(PE.EDateTime,'yyyyMMddhhmm') as varchar(50))+'AM'
when (PE.ADate is not NULL and cast(PE.ADate as time) < '12:30') then cast(format(PE.ADate,'yyyyMMddhhmm') as varchar(50))+'AM'
when (PE.EDateTime is not NULL and cast(PE.EDateTime as time) >= '12:30') THEN cast(format(PE.EDateTime,'yyyyMMddhhmm') as varchar(50))+'PM'
when (PE.ADate is not NULL and cast(PE.ADate as time) > '12:30') then cast(format(PE.ADate,'yyyyMMddhhmm') as varchar(50))+'PM'
else null
end) as SNumber,
case
when (SNumber like'%AM') then 'AM'
when SNumber like '%PM') then 'PM'
else null
end as [Session],
Comments
from (
select
PE1.RId,
PE1.ADate,
PE1.EDateTime
from (
select
RegEId,
ADate,
EDateTime,
Comments
from PatEnr
where PreNumber is not null
) as PE1
left join Pat PEA
on PE1.RegEId = PEA.RegEId
left join PBooking PB
on PB.RegEId = PE1.RegEId
) as PE
我想在下面的同一查询中使用SNumber,但我无法使用它,因为这都属于一个查询。有没有办法在下面的CASE 中使用上面的内容?我想使用类似下面的东西。
case
when (SNumber like'%AM') then 'AM'
when (SNumber like '%%PM') then 'PM'
else null
end as Session,
【问题讨论】:
-
在整个查询的上下文中查看总体需求可能很有用。可能有几种不同的方法可以实现这一目标。您可以将 CASE 表达式放入一个标量类型的用户定义函数(这使得在其他查询中更容易重用),或者您可以将 CASE 表达式合并到一个公共表表达式 (CTE) 中,然后从 (并应用您进一步的 CASE 逻辑)。或者您可以将现有的 CASE 表达式包装在 RIGHT(
, 2) 中,因为这似乎基本上是您想要实现的目标 -
旁白:您可能需要考虑使用
Coalesce( PE.EDateTime, PE.ADate )来简化您的case表达式。
标签: sql sql-server tsql