在某一天获得第一次预约

时间:2017-09-21 14:30:04

标签: sql tsql

我可以使用以下查询来提取发生的约会列表:

SELECT
   host
  ,name
  ,apt_time
FROM
   table
ORDER BY apt_time

我会得到:

host   name   apt_time
sam    bob    2017-01-01 08:00:00.000
sam    joe    2017-01-01 12:00:00.000
sam    tim    2017-01-05 09:00:00.000
sam    kay    2017-01-05 14:00:00.000

但是,我只是希望看到主持人每天看到的第一个约会,以获得类似的内容:

host   name   apt_time
sam    bob    2017-01-01 08:00:00.000
sam    tim    2017-01-05 09:00:00.000

第一次约会的干净方法是什么?

3 个答案:

答案 0 :(得分:3)

一个选项是使用WITH TIES子句与Row_Number()

一起使用
Select Top 1 with ties 
       host
      ,name
      ,apt_time
 From  YourTable
 Order By Row_Number() over (Partition By host,cast(appt_time as date) Order by appt_time)

答案 1 :(得分:2)

您可以使用ROW_NUMBERPARTITION BY主机名以及日期时间的日期部分,如下所示:

WITH CTE
AS
(
  SELECT
    host,name,apt_time,
    ROW_NUMBER() OVER(PARTITION BY host,CAST(apt_time AS DATE) 
                      ORDER BY apt_time) AS RN
  FROM table1
)
SELECT host, name, apt_time 
FROM CTE 
WHERE  RN =1

demo

| host | name |             apt_time |
|------|------|----------------------|
|  sam |  bob | 2017-01-01T08:00:00Z |
|  sam |  tim | 2017-01-05T09:00:00Z |

答案 2 :(得分:0)

WITH 
 tmp1 AS (
   SELECT host, name, to_char(apt_time, 'YYYY-mm-dd') as apt_day, apt_time FROM logins
 ),
 tmp2 AS (
   SELECT host, name, apt_day, row_number() over (partition by host, apt_day order by apt_time asc) as p_rank FROM tmp1
 )
SELECT host, apt_day, name FROM tmp2 WHERE p_rank = 1;

 host |  apt_day   | name
------+------------+------
 foo  | 2017-01-05 | kay
 sam  | 2017-01-01 | bob
 sam  | 2017-01-05 | tim
(3 Zeilen)

(编辑:将rank()更改为row_number(),因为如果apt_date相同,后者可以返回多行,这在理论上是不可能的)