复杂查询的输出列

时间:2017-07-25 06:56:55

标签: sql sql-server-2014

我想问一下如何使用tickerID输出一列。

截至目前,我有以下内容:

select distinct 
    mtime,  
    avg(lastBid) Bid ,
    avg(lastAsk) Ask 
from 
    (Select 
         a.mtime, a.IntradayTime, f.lastBid, f.lastAsk 
     from 
         (select 
              cte.*, 
              (select top 1 datetime 
               from IntradayHistory_1min.dbo.IntradayDataHistory' + @product + '_1min' + ' 
               where datetime <= cte.mtime 
                 and TickerID = ' + cast(@ticker as nvarchar(24)) + ' 
               order by datetime desc) as IntradayTime 
          from 
              cte) a 
    left join 
        Intradayhistory_1min.dbo.IntradayDataHistory'+ @product + '_1min' + ' f on f.datetime = a.IntradayTime and f.tickerid = ' + cast(@ticker as nvarchar(24)) + ') b 
group by 
    mtime 
order by 
    mtime 
option (maxrecursion 0)

dbo.IntradayDataHistory_Rebar_1min的屏幕截图(在这种情况下:Rebar是@product):

enter image description here

已更新以澄清:输出看起来像这样,

enter image description here

我也尝试过以下操作,但是没有用:

select distinct mtime,
(ticker) tickerid
avg(lastBid) Bid ,
avg(lastAsk) Ask 

from ( Select a.mtime, a.IntradayTime, f.tickerid, f.lastBid, f.lastAsk 
from (select cte.*, (select top 1 datetime from IntradayHistory_1min.dbo.IntradayDataHistory' + @product + '_1min' + ' 
where datetime <= cte.mtime and TickerID = ' + cast(@ticker as nvarchar(24)) + ' order by datetime desc) as IntradayTime from cte ) a 
left join Intradayhistory_1min.dbo.IntradayDataHistory'+ @product + '_1min' + ' f 

on f.datetime = a.IntradayTime and f.tickerid = ' + cast(@ticker as nvarchar(24)) + ' ) b 
group by mtime order by mtime option (maxrecursion 0)

我得到的错误:

  

列'b.tickerid'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

1 个答案:

答案 0 :(得分:0)

我发现解决方案是在ticker前面添加一个avg函数,如下所示:

select distinct mtime,
avg(ticker) tickerid
avg(lastBid) Bid ,
avg(lastAsk) Ask 

from ( Select a.mtime, a.IntradayTime, f.tickerid, f.lastBid, f.lastAsk 
from (select cte.*, (select top 1 datetime from IntradayHistory_1min.dbo.IntradayDataHistory' + @product + '_1min' + ' 
where datetime <= cte.mtime and TickerID = ' + cast(@ticker as nvarchar(24)) + ' order by datetime desc) as IntradayTime from cte ) a 
left join Intradayhistory_1min.dbo.IntradayDataHistory'+ @product + '_1min' + ' f 

on f.datetime = a.IntradayTime and f.tickerid = ' + cast(@ticker as nvarchar(24)) + ' ) b 
group by mtime order by mtime option (maxrecursion 0)

背后的原因在于:Column "invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause"