我试图运行一个SQL查询来显示1行而不是不同行的日期,我还需要确定每个显示日期之间的天数。
请在下面找到当前查询。
SELECT "Pat_Name",
CASE WHEN "vw_Schedule"."Activity" = '123'
THEN "vw_Schedule"."App_DtTm"
ELSE NULL
END as Consult,
CASE WHEN "vw_Schedule"."Activity" = '456'
THEN "vw_Schedule"."App_DtTm"
ELSE NULL
END as SIM,
CASE WHEN "vw_Schedule"."Activity" = '789'
THEN "vw_Schedule"."App_DtTm"
ELSE NULL
END as PLANNING,
CASE WHEN "vw_Schedule"."SysDefStatus" = 'SC'
THEN "vw_Schedule"."App_DtTm"
ELSE NULL
END as TreatmentStart,
CASE WHEN "vw_Schedule"."SysDefStatus" = 'FC'
THEN "vw_Schedule"."App_DtTm"
ELSE NULL
END as TreatmentFinished
FROM "vw_Schedule"
WHERE "vw_Schedule"."Activity"='123'
or "vw_Schedule"."Activity"='456'
or "vw_Schedule"."Activity"='789'
or "vw_Schedule"."SysDefStatus"='SC'
or "vw_Schedule"."SysDefStatus"='FC'
我希望输出类似于下面的
Pat_Name | Consult | Days | SIM | Days | PLANNING | Days | TreatmentStart | Days | TreatmentFinish
Test Pat | 1/9/2013 | 4 | 5/9/2013 | 10 | 15/9/2013 | 3 | 18/9/2013 | 7 | 25/9/2013
感谢您的帮助。
答案 0 :(得分:0)
如果您可以保证每个pat_Name每个活动只有一行,那么您可以安全地使用聚合函数为每个pat_name获取每个活动的App_dtTm,而不必担心丢失数据。如果没有重复,你也可以使用MIN或MAX。
SELECT s.Pat_Name,
Consult = MAX(CASE WHEN s.Activity = '123' THEN s.App_DtTm END),
SIM = MAX(CASE WHEN s.Activity = '456' THEN s.App_DtTm END),
PLANNING = MAX(CASE WHEN s.Activity = '789' THEN s.App_DtTm END),
TreatmentStart = MAX(CASE WHEN s.SysDefStatus = 'SC' THEN s.App_DtTm END),
TreatmentFinished = MAX(CASE WHEN s.SysDefStatus = 'FC' THEN s.App_DtTm END)
FROM vw_Schedule s
WHERE s.Activity IN ('123', '456', '789')
OR s.SysDefStatus IN ('SC', 'FC')
GROUP BY s.Pat_Name;
如果您可以为单个活动设置重复日期,那么无论您使用MIN还是MAX,它都会有所不同。
要获取活动之间的日期,您可以将上述查询移动到公用表表达式(或者您喜欢的子查询),并简单地引用您创建的列:
WITH T AS
( SELECT s.Pat_Name,
Consult = MAX(CASE WHEN s.Activity = '123' THEN s.App_DtTm END),
SIM = MAX(CASE WHEN s.Activity = '456' THEN s.App_DtTm END),
PLANNING = MAX(CASE WHEN s.Activity = '789' THEN s.App_DtTm END),
TreatmentStart = MAX(CASE WHEN s.SysDefStatus = 'SC' THEN s.App_DtTm END),
TreatmentFinished = MAX(CASE WHEN s.SysDefStatus = 'FC' THEN s.App_DtTm END)
FROM vw_Schedule s
WHERE s.Activity IN ('123', '456', '789')
OR s.SysDefStatus IN ('SC', 'FC')
GROUP BY s.Pat_Name
)
SELECT Pat_Name,
Consult,
Days = DATEDIFF(DAY, Consult, SIM),
SIM,
Days = DATEDIFF(DAY, SIM, PLANNING),
PLANNING,
Days = DATEDIFF(DAY, PLANNING, TreatmentStart),
TreatmentStart,
Days = DATEDIFF(DAY, TreatmentStart, TreatmentFinish),
TreatmentFinish
FROM T;