我使用此代码创建了一个名为TaxLots
的表:
CREATE TABLE Portfolio.TaxLots
(
Ticker varchar(22) NOT NULL,
SecurityDescription varchar(50) NOT NULL,
Class varchar(15) NULL,
Ccy varchar(5) NULL,
LSPosition char(3) NULL,
Date date NULL,
Quantity int NULL,
LocAvgCost decimal(8,3) NULL,
LocTaxCostBasis int NULL,
LocMktVal int NULL,
BaseAvgCost decimal(8,3) NULL,
BaseTaxCostBasis int NULL,
BaseMktVal int NULL,
BaseUNRL int NULL,
DateCreated DATE NOT NULL DEFAULT Cast(GetDate() as Date)
)
GO
然后我使用以下代码创建了第二个名为BusinessDates
的表:
CREATE TABLE Portfolio.BusinessDates
(
Date date NOT NULL,
)
GO
我使用所有相关数据填充了两个表,现在我想创建一个名为TaxLotsHistory
的视图,其中包含Taxlots
表中的所有列以及另一个名为ReportDate
的列从BusinessDates
之前的DateCreated
表中提取最后一个营业日期。
例如:如果DateCreated
日期为2016-08-15
,则ReportDate
应为2016-08-12
。从逻辑上讲,
ReportDate = Max(BusinessDate)
where BusinessDate < DateCreated
但由于BusinessDate
和DateCreated
位于两个单独的表中,因此我无法弄清楚语法。我有一些类似的东西,但它不起作用:
CREATE VIEW Portfolio.TaxLotsHistory
AS
SELECT
Ticker, SecurityDescription, Class, Ccy, LSPosition, Date, Quantity,
LocAvgCost, LocTaxCostBasis, LocMktVal, BaseAvgCost, BaseTaxCostBasis,
BaseMktVal, BaseUNRL, DateCreated,
(SELECT MAX(BusinessDate)
FROM Portfolio.BusinessDates D As ReportDate
WHERE D.BusinessDate) < T.DateCreated
FROM
Portfolio.TaxLots T
我目前正在
关键字&#39; AS&#39;附近的语法错误不正确
但我确定代码还有其他问题。感谢。
答案 0 :(得分:2)
试试这个
CREATE VIEW Portfolio.TaxLotsHistory
AS
Select Ticker, SecurityDescription, Class, Ccy, LSPosition, Date, Quantity,
LocAvgCost, LocTaxCostBasis, LocMktVal, BaseAvgCost, BaseTaxCostBasis,
BaseMktVal, BaseUNRL, DateCreated,
( Select Max(D.BusinessDate)
From Portfolio.BusinessDates D
Where D.BusinessDate) < T.DateCreated ) As ReportDate
From Portfolio.TaxLots T
答案 1 :(得分:1)
使用Apply ..
Create view vwname as
Select Ticker, SecurityDescription, Class, Ccy, LSPosition, Date, Quantity,
LocAvgCost, LocTaxCostBasis, LocMktVal, BaseAvgCost, BaseTaxCostBasis,
BaseMktVal, BaseUNRL, DateCreated,b.reportdate
from
Portfolio.TaxLots t
cross apply
(
(Select Max (BusinessDate) As ReportDate From Portfolio.BusinessDates D
Where D.BusinessDate) < T.DateCreated
) b