sql - how to get around problems with group by, aggregate -


i have following query:

select d.currentdate, t.configid, t.value value    #dates d         outer apply         (   select  t.value value, t.fk_shipdatasubsystemconfigid                mytable t               t.[timestamp] <= d.currentdate , t.configid in (' + @idlist + ')             , t.fk_datasystemid <> 1         ) t  group d.currentdate, t.configid ) 

where dates table holding bunch of datetimes using ensure data @ intervals need.

my problem group by clause. query doesn't work because value not in group by or aggregate function. tried grouping value make error go away, gives me every single date in interval selecting on matched every single value -- not want. should end table 1 row each date/configid pairing.

when remove value select , date , configid, works fine. exact number of rows should getting.

the table i'm pulling looks this:

pk_dataid    timestamp        value     configid 1            1/1/2015 12:00   234       5 2            1/1/2015 12:01   456       4 

i expecting this:

timestamp            value        configid 1/1/2015 12:00:00    234          5 1/1/2015 12:00:00    456          4 

where have value each configid/date pair every fifteen minutes. when add max(value) 1 value every time instead of different ones. when group value millions of rows, looks getting 1 row each timestamp matched each value other timestamp. don't understand happening.

how can results while selecting value?

if understand correctly, want top 1 in apply:

select d.currentdate, t.configid, t.value value #dates d outer apply      (select  top 1 t.value value, t.fk_shipdatasubsystemconfigid          mytable t         t.[timestamp] <= d.currentdate ,               t.configid in (' + @idlist + ') ,               t.fk_datasystemid <> 1      order t.[timestamp] desc     ) t ; 

edit:

if need 1 row each config , time:

select d.currentdate, t.configid, t.value value #dates d cross join      (select distinct fk_shipdatasubsystemconfigid       mytable       t.configid in (' + @idlist + ')      ) c outer apply      (select  top 1 t.value value, t.fk_shipdatasubsystemconfigid          mytable t         t.[timestamp] <= d.currentdate ,               t.configid = c.fk_shipdatasubsystemconfigid ,               t.fk_datasystemid <> 1       order t.[timestamp] desc      ) t ; 

same basic idea, needs generate rows configs , dates before outer apply.


Comments