如何从sql表中检索最后n个null值?

时间:2018-07-19 15:01:40

标签: sql sql-server

我有这样的桌子。由此,我想要错过了最后3次约会的客户名称(表示他最近3次访问日期为空)。

+---------+------------------------+------------------------+
|Customer  |appointmentDate         |Vstdate                 |
+---------+------------------------+------------------------+
|a        |2017-01-01 00:00:00.000 |2017-01-01 10:42:33.793 |
|a        |2017-01-30 17:40:00.000 |NULL                    |
|a        |2017-01-30 17:40:00.000 |2017-01-30 19:52:39.000 |
|a        |2017-02-01 20:50:00.000 |2017-02-01 17:37:12.000 |
|a        |2013-02-14 12:20:59.407 |NULL                    |
|b        |2017-03-02 00:00:00.000 |2017-03-02 13:17:13.000 |
|b        |2017-03-25 12:30:00.000 |2017-03-25 14:30:00.000 |
|b        |2017-04-23 10:20:00.000 |NULL                    |
|b        |2017-05-27 12:30:00.000 |NULL                    |
|b        |2017-10-01 00:00:00.000 |NULL                    |
|c        |2017-03-02 00:00:00.000 |2017-03-02 13:17:13.000 |
|c        |2017-01-01 00:00:00.000 |2017-01-01 10:42:33.793 |
|c        |2017-01-30 17:40:00.000 |NULL                    |
|c        |2017-01-30 17:40:00.000 |2017-01-30 19:52:39.000 |
+---------+------------------------+------------------------+

例如,在上表中,只有客户b错过了他的最后3个约会(意味着他的最近3个访问日期为空)。我只希望从桌子上重试他的名字。

2 个答案:

答案 0 :(得分:1)

使用top 3

select distinct customer from tmp c where (
  select max(vstdate) from (
    select top 3 vstdate from tmp e where e.customer = c.customer
    order by appointmentDate desc
  ) x
) is null;

结果:

customer  
----------
b         

答案 1 :(得分:0)

使用窗口功能:

declare @tmp table(Customer varchar(1), appointmentDate datetime2, Vstdate datetime2)
insert into @tmp values
 ('a', '2017-01-01 00:00:00.000', '2017-01-01 10:42:33.793')
,('a', '2017-01-30 17:40:00.000', NULL                     )
,('a', '2017-01-30 17:40:00.000', '2017-01-30 19:52:39.000')
,('a', '2017-02-01 20:50:00.000', '2017-02-01 17:37:12.000')
,('a', '2013-02-14 12:20:59.407', NULL                     )
,('b', '2017-03-02 00:00:00.000', '2017-03-02 13:17:13.000')
,('b', '2017-03-25 12:30:00.000', '2017-03-25 14:30:00.000')
,('b', '2017-04-23 10:20:00.000', NULL                     )
,('b', '2017-05-27 12:30:00.000', NULL                     )
,('b', '2017-10-01 00:00:00.000', NULL                     )
,('c', '2017-03-02 00:00:00.000', '2017-03-02 13:17:13.000')
,('c', '2017-01-01 00:00:00.000', '2017-01-01 10:42:33.793')
,('c', '2017-01-30 17:40:00.000', NULL                     )
,('c', '2017-01-30 17:40:00.000', '2017-01-30 19:52:39.000')

select t.Customer 
from (
    select *, row_number() over (partition by Customer order by appointmentDate desc) as ord
    from @tmp
) t
where t.ord <= 3 
group by t.Customer
having max(t.Vstdate) is null

结果:

enter image description here