sql server—这可以作为sql视图来完成吗

vd2z7a6w  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(303)

我有一个客户事件的sql server表:

CREATE TABLE CustomerEvent
(
    CustomerID int,
    EventType int,
    EventDate datetime
)

同一个客户在一天内可以有许多事件类型。
事件类型如下
1-签入
2-结帐
3-examstart
4-检查
现在我要选择当前(今天)在本地的客户。这是那些已经入住但还没有退房的客户,不管他们是否正在参加考试。这可以作为一个sql视图来完成吗,或者我必须为此编写一个存储过程吗?

nnt7mjpx

nnt7mjpx1#

你想要今天。所以我建议 not exists :

select ce.customerid
from customerevent ce
where eventtype = 1 and
      event_date >= current_date and
      event_date < current_date + interval '1 day' and
      not exists (select 1
                  from customerevent ce2
                  where ce2.customerid = ce.customerid and
                        ce2.eventtype = 2 and
                        ce2.eventdate > ce.eventdate
                 );

您可以轻松地将其合并到视图中。
注意:日期/时间函数是众所周知的特定于数据库的,因此“today”的确切语法可能会有所不同。
编辑:
在sql server中,这可以写成:

select ce.customerid
from customerevent ce
where eventtype = 1 and
      convert(date, event_date) >= concat(date, current_date) and
      not exists (select 1
                  from customerevent ce2
                  where ce2.customerid = ce.customerid and
                        ce2.eventtype = 2 and
                        ce2.eventdate > ce.eventdate
                 );
amrnrhlw

amrnrhlw2#

您可以使用聚合,并使用 having 比较每位客户最后一次入住和最后一次退房的条款:

create view customerview as
select customerid
from customerevent
group by customerid
having 
    max(case when eventtype = 1 then eventdate end) 
        > max(case when eventtype = 2 then eventdate end)
    or (
        max(case when eventtype = 1 then eventdate end) is not null
        and max(case when eventtype = 2 then eventdate end) is null
    )

中的第二个条件 having 条件处理至少签入一次但从未 checkout 的客户。
我们可以使用 coalesce() 以及确定在表中任何行之前的固定日期:

having max(case when eventtype = 1 then eventdate end) 
    > max(case when eventtype = 2 then eventdate else '19700101' end)

相关问题