0

我试图运行 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

谢谢你的帮助。

4

1 回答 1

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;
于 2013-10-09T09:15:26.600 回答