在连接表时使用子查询并在WHERE子句中过滤

时间:2017-04-03 17:41:54

标签: sql-server join

SELECT DISTINCT(t1.Ticker),t2.SecurityID,t2.ClosePrice,t2.QuoteDateTime FROM [Hub].[SecurityMaster].[SecurityMasterDetails] as t1 
                INNER JOIN [Hub].[SecurityMaster].[SecurityPrices] as t2 
                ON t2.SecurityID =t1.SecurityID 
                WHERE t2.QuoteDateTime IN (SELECT max(QuoteDateTime) FROM [Hub].[SecurityMaster].[SecurityPrices]) AND t1.SecurityTypeName = 'REIT'

我得到一个没有数据的输出。子查询不与WHERE子句中的其他过滤器一起运行。我不确定我做错了什么。有人可以帮忙!

3 个答案:

答案 0 :(得分:0)

如果您尝试为每个SecurityPrices获取Ticker的最新行,则可以选择使用cross apply()

select --distinct /* distinct not needed if `Ticker` is unique on `smd`
   smd.Ticker
 , sp.SecurityID
 , sp.ClosePrice
 , sp.QuoteDateTime
from [Hub].[SecurityMaster].[SecurityMasterDetails] as smd
  cross apply (
    select top 1 
        i.SecurityID
      , i.ClosePrice
      , i.QuoteDateTime
    from [Hub].[SecurityMaster].[SecurityPrices] i
    where i.SecurityID = smd.SecurityID
    order by i.QuoteDateTime desc
    ) as sp
where SecurityTypeName = 'REIT' /* which table does this column belong to? */

答案 1 :(得分:0)

由于max(QuoteDateTime)记录没有SecurityTypeName = 'REIT',因此无法获得结果。我想你想要max(QuoteDateTime) SecurityTypeName,所以这可以通过INNER JOIN完成。

SELECT DISTINCT
    (t1.Ticker),
    t2.SecurityID,
    t2.ClosePrice,
    t2.QuoteDateTime 
FROM [Hub].[SecurityMaster].[SecurityMasterDetails] as t1 
    INNER JOIN [Hub].[SecurityMaster].[SecurityPrices] as t2 
    ON t2.SecurityID =t1.SecurityID 
    INNER JOIN 
    (SELECT max(QuoteDateTime) DT FROM [Hub].[SecurityMaster].[SecurityPrices]) P on P.DT =  t2.QuoteDateTime
WHERE SecurityTypeName = 'REIT'

修改

我怀疑你的数据不符合你的想法。这是你如何检查...

--Find the SecurityID that matches the max date
SELECT 
    SecurityID , 
    max(QuoteDateTime) DT 
FROM [Hub].[SecurityMaster].[SecurityPrices]
GROUP BY SecurityID

--I'm betting this ID isn't in your SecurityMasterDetails where the Type is REIT
SELECT DISTINCT
    SecurityID
FROM SecurityMasterDetails
WHERE SecurityTypeName = 'REIT'

由于第一个查询中返回的SecurityID不在第二个查询结果集中,因此您将获得NULL结果。

答案 2 :(得分:0)

我认为您的查询将是

SELECT DISTINCT TOP 1 WITH TIES 
                      t1.Ticker,
                      t2.SecurityID,
                      t2.ClosePrice,
                      t2.QuoteDateTime 
FROM [Hub].[SecurityMaster].[SecurityMasterDetails] as t1 
     INNER JOIN [Hub].[SecurityMaster].[SecurityPrices] as t2 ON t2.SecurityID =t1.SecurityID 
WHERE SecurityTypeName = 'REIT'
ORDER BY t2.QuoteDateTime DESC