在单个查询中选择Top / bottom 2值(/ with subquery)

时间:2014-05-08 06:46:40

标签: sql sql-server-2008 datetime

请考虑以下查询:

SELECT personeelsnr,
  CAST(tijdstip AS DATE) AS Dag,
  MIN(tijdstip) AS MiddagIn,
  MAX(tijdstip) AS MiddagUit,
  DATEDIFF(MINUTE, MIN(tijdstip),MAX(tijdstip)) AS Middagpauze
FROM [STI].[DBO].[STI_Entry]
WHERE (tijdstip BETWEEN @DateFrom AND @DateTo
AND ((DATEPART(hh, tijdstip) BETWEEN 12 AND 13)
OR CAST(tijdstip AS TIME)        = '14:00:00'))
AND ( (personeelsnr              = @personeelsNr
AND (LEN(RTRIM(@leveranciersnr)) = 0
OR @leveranciersnr              IS NULL))
OR (indienstfirmanr              = @leveranciersnr
AND LEN(RTRIM(@leveranciersnr))  > 0) )
GROUP BY personeelsnr,
  naam,
  voornaam,
  CAST(tijdstip AS DATE) )

我想要实现的是MIN(tijdstip) as MiddagIn, MAX(tijdstip) as MiddagUit而不是2 tijdstip我希望得到底部 e.g MIN(tijdstip) as MiddagIn, MIN(tijdstip) as MiddagUit where MiddagIn <> MiddagUit and MiddagIn < Middaguit For instance Person A has records for Day 1 as follows 12:01:00 12:07:00 12:30:37 12:57:00

subquery

我当前的解决方案为我提供了 12:01:00(作为MIN) 12:57:00(作为MAX)。但我希望 12:01:00(作为MIN) 12:07:00(作为MAX)

我知道使用{{1}}执行此操作,但我在不使用子查询的情况下搜索正确的解决方案。有人能指出我正确的方向吗?

thnx everyone

1 个答案:

答案 0 :(得分:2)

  

例如,人员A有第1天的记录,如下所示

12:01:00
12:07:00
12:30:37
12:57:00 
     

我目前的解决方案给了我12:01:00(作为MIN)和12:57:00(作为MAX)。   但我想要12:01:00(作为MIN)和12:07:00(作为MAX)

如果您的样本代表您的数据,请尝试以下sql:

with cte as
(
    select 
        ROW_NUMBER() over(order by a.tijdstip) as id
        ,a.tijdstip
    from @temp a
)
select 
    c.id, c.tijdstip as 'MIN',
    c2.tijdstip as 'Max'
from cte c left join cte c2 on c.id = c2.id-1
where (c.id % 2) <> 0

--RESULT
/*
id                   MIN             Max
-------------------- --------------- ---------------
1                    12:01:00        12:07:00
3                    12:30:37        12:57:00

*/

ood row id将变为MIN,偶数行id将变为MAX