我有一个表ValuationHistory
,其中包含以下列
Code | ValuationDate | NetAssetValue | PricePerShare | Subscriptions | Redemptions
ABC | 2014-06-30 | 12546.50 | 100.23 | 60 | 70
CEF | 2014-06-30 | 10025.20 | 120.50 | 30 | 20
ABC | 2014-07-31 | 12505.50 | 101.50 | 40 | 60
ABC | 2014-08-31 | 13051.41 | 102.50 | 35 | 70
现在,用户将从aspx页面中选择评估日期和代码。我想编写一个sql查询,它将为我提供一个报告,其中包含用户选择的评估日期之前的所有评估日期的以下列
Code | BeginningEquity | Subscriptions | Redemptions | EndingEquity
哪里
Code
是用户选择的代码BeginningEquity
是以前估值的NetAssetValue
Subscriptions
很直接Redemptions
很直接EndingEquity
是NetAssetValue
valuationDate
我首先创建了一个名为@ValDates
的表变量,并将所有评估日期记录到此临时表中。然后我与@ValDates
表进行了ValuationHistory
的连接。
但是我在以下查询中收到错误。错误消息是:
子查询返回了多个值
有人可以帮助我以更好的方式编写此查询吗
SELECT (SELECT NetAssetValue
FROM ValuationHistory
WHERE ValuationDate IN (SELECT Max(ValuationDate)
FROM ValuationHistory
WHERE ValuationDate < nd.ValuationDate)),
Subscriptions,
Redemptions,
EndingEquity
FROM ValuationHistory vh
INNER JOIN @ValDates vd
ON vh.ValuationDate = vd.ValuationDate
WHERE vh.Code = @Code
AND vh.ValuationDate < = @ValuationDate
答案 0 :(得分:0)
我对你的要求不是很清楚。根据说明,您可以尝试按以下方式开始查询
DECLARE @Code VARCHAR(10) = 'ABC'
,@ValuationDate date = '2014-07-31'
;WITH cte AS (
SELECT
rn = ROW_NUMBER() OVER (PARTITION BY Code ORDER BY ValuationDate), *
FROM ValuationHistory
)
SELECT
c1.Code,
c2.NetAssetValue AS BeginningEquity,
c2.ValuationDate AS BeginningDate,
c1.NetAssetValue AS EndingEquity,
c1.ValuationDate AS EndingDate,
c1.[Subscriptions],
c1.[Redemptions]
from cte c1
LEFT JOIN cte c2
ON c1.Code = c2.Code
AND c2.rn = c1.rn - 1
WHERE c1.Code = @Code
AND c1.ValuationDate < = @ValuationDate