Sql server 连接表时在WHERE子句中使用子查询和筛选器
我得到一个没有数据的输出。子查询不会与WHERE子句中的其他筛选器一起运行。我不确定我做错了什么。有人能帮忙吗 如果您试图从Sql server 连接表时在WHERE子句中使用子查询和筛选器,sql-server,join,Sql Server,Join,我得到一个没有数据的输出。子查询不会与WHERE子句中的其他筛选器一起运行。我不确定我做错了什么。有人能帮忙吗 如果您试图从SecurityPrices中获取每个Ticker的最新行,一个选项是使用cross apply(): 您没有得到结果,因为max(QuoteDateTime)记录没有SecurityTypeName='REIT'。我想您需要这个SecurityTypeName的max(QuoteDateTime),因此这可以通过内部连接来完成 select --distinct /* d
SecurityPrices
中获取每个Ticker
的最新行,一个选项是使用cross apply()
:
您没有得到结果,因为
max(QuoteDateTime)
记录没有SecurityTypeName='REIT'
。我想您需要这个SecurityTypeName
的max(QuoteDateTime)
,因此这可以通过内部连接来完成
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? */
编辑
我怀疑你的数据没有你认为的那样。以下是您可以检查的方式
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'
由于第一个查询中返回的SecurityID不在第二个查询结果集中,因此将得到NULL结果 我想你的问题是
--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'
所以您想做什么?在join和where子句之后可以返回结果的所有表中都有有效数据吗?很抱歉,SecurityTypeName取自表t1-[Hub].[SecurityMaster].[SecurityMasterDetails]问题是,数据库中的日期没有按照最近的日期排序。很抱歉,我之前没有正确指定它,QuoteDateTime和SecurityTypeName不是来自同一个表。我不明白为什么,但我的输出中没有任何数据。原因与@SmithaShivakumar之前相同。max(QuoteDateTime)记录的SecurityID不是REIT SecurityID。啊!你建议我做什么?检查我刚做的编辑。您的查询运行正常,因为所有这些查询都是正确的。您不能让数据集返回不存在或不符合@SmithaShivakumar条件的内容
--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'
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