2015-11-25 45 views
0

我期待从组中获得主键。SQL聚合密钥并获取主键

我在找的是选择所有最高和最低温度一天,并获得该条目的主键。

select Cast(DateTime as date) AS 'Date', MAX(Temperature) AS 'Max Temperature' 
from [Testing].[dbo].[Reading] 
GROUP by Cast(DateTime as date) 
ORDER by Cast(DateTime as date) 

这会发现我每一天的最高温度不过由于小组由我无法获取该条目是最高的这一天的主键。 任何帮助?

+1

如果什么有更多的读数相同的温度? Dublicate? [获取具有列的最大值的行](http://stackoverflow.com/questions/121387/fetch-the-row-which-has-the-max-value-for-a-column) –

+0

这种情况下,我关心它一天的最高温度,如果发生一次或两次没有关系 – RobouteGuiliman

+0

好吧,如果有重复你想要哪一个? –

回答

0

基于@Gordon答案:

select Cast(DateTime as date) AS [Date], Temperature AS MaxTemperature,  id_temperature 
from (select r.*, 
      row_number() over (partition by Cast(DateTime as date) 
           order by DateTime desc, Temperature desc) as seqnum 
     from [Testing].[dbo].[Reading] r 
    ) r 
order by Cast(DateTime as date); 
0

一种方法是使用窗口函数和条件汇总:

select Cast(DateTime as date) AS [Date], MAX(Temperature) AS MaxTemperature, 
     max(case when seqnum = 1 then temperature end) as LastTemperature 
from (select r.*, 
      row_number() over (partition by Cast(DateTime as date) 
           order by DateTime desc) as seqnum 
     from [Testing].[dbo].[Reading] r 
    ) r 
group by Cast(DateTime as date) 
order by Cast(DateTime as date); 

编辑:

如果你想从最高气温行其他值,那么你可以使用:

select Cast(DateTime as date) AS [Date], MAX(Temperature) AS MaxTemperature, 
     max(case when seqnum_max = 1 then <whatever column here> end) as <whatever column> 
from (select r.*, 
      row_number() over (partition by Cast(DateTime as date) 
           order by Temperature desc) as seqnum_max 
     from [Testing].[dbo].[Reading] r 
    ) r 
group by Cast(DateTime as date) 
order by Cast(DateTime as date); 

您可以使用另一个变量作为最小值。

+0

这不给我最高温度来自的主键 – RobouteGuiliman

+0

它很好,只需通过'''Temperature AS MaxTemperature'''改变'''MAX(Temperature)AS MaxTemperature''并改变'''通过DateTime desc''的顺序由'''按照DateTime desc,Temperature desc''的顺序对分区进行分区并将其移除 –