加入一张桌子

时间:2014-09-25 12:13:04

标签: sql-server-2008 join

我有一个表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很直接
  • EndingEquityNetAssetValue
  • 上的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 

1 个答案:

答案 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 

SQL Fiddle Demo