【问题标题】:What script would return the required final table?什么脚本会返回所需的决赛桌?
【发布时间】:2014-07-02 10:05:19
【问题描述】:

在下表中,哪个脚本会为每个 CARE_ID 返回一行,其中 CP 的 EVENT_TYPE 在 TR 的第一个实例之前。否则返回最近的 CP 实例。优先比较器是 EVENT_DATE 并且联络断路器是 MAX(EVENT_ID) 以下是预期的决赛桌。

CARE_ID     EVENT_ID    EVENT_DATE          EVENT_TYPE
3           117         09/04/2010 00:00    CP
3           104         11/04/2010 00:00    TR
3           190         16/04/2010 00:00    TR
3           16          12/07/2010 00:00    TR
3           17          13/07/2010 00:00    TR
3           18          13/07/2010 00:00    TR
78          11          27/07/2009 00:00    TR
78          9           28/07/2009 00:00    TR
78          706         08/12/2010 00:00    CP
78          707         09/12/2010 00:00    CP
107         93          23/02/2010 00:00    CP
107         1474        21/09/2012 00:00    TR
206         84          28/07/2009 00:00    CP
206         85          21/08/2009 00:00    CP


CARE_ID     EVENT_ID    EVENT_DATE          EVENT_TYPE
3           117         09/04/2010 00:00    CP
78          707         09/12/2010 00:00    CP
107         93          23/02/2010 00:00    CP
206         85          21/08/2009 00:00    CP

【问题讨论】:

  • @Gordon Linoff - 感谢您的编辑 - 这个脚本可行吗?

标签: sql sql-server tsql sql-server-2000


【解决方案1】:

这种类型的查询应该是可能的。以下获取最大事件日期,视您的条件而定:

select t.care_id,
       coalesce(max(case when event_date < tr.mined then event_date end),
                max(event_date)
               ) as thedate
from table t left outer join
     (select care_id, min(event_date) mined
      from table t
      where event_type = 'TR'
      group by care_id
     ) tr
     on tr.care_id = t.care_id
where t.event_type = 'CP'
group by t.care_id;

然后您可以连接回原始表以获取其余信息:

select t.*
from table t join
     (select t.care_id,
             coalesce(max(case when event_date < tr.mined then event_date end),
                      max(event_date)
                     ) as thedate
      from table t left outer join
           (select care_id, min(event_date) mined
            from table t
            where event_type = 'TR'
            group by care_id
           ) tr
           on tr.care_id = t.care_id
      where t.event_type = 'CP'
      group by t.care_id
     ) tt
     on tt.care_id = t.care_id and tt.thedate = t.event_date and tt.event_type = 'CP';

【讨论】:

  • 谢谢,第一个脚本运行良好,除了缺少的 event_id 之外,还返回了所需的结果。然而,第二个脚本将不起作用,因为 care_id 和 event_date 的组合不一定是唯一的,因此加入原始表将为每个 care_id 生成多行。是否可以操纵第一个脚本以包含 EVENT_ID?那将是乌托邦!
  • @PaulStevens 。 . .我认为第二个查询现在对您有用。但是,您应该有一个自动递增的主键,以便可以唯一标识每个表。
猜你喜欢
  • 1970-01-01
  • 2020-09-13
  • 2021-04-13
  • 1970-01-01
  • 2014-02-08
  • 2018-07-06
  • 2013-08-21
  • 1970-01-01
相关资源
最近更新 更多