我有两张我正在使用的桌子。第一个QuarterDateMapping
持有约四分之三的开始和结束日期的信息:如何根据另一个查询的输出来选择行?
GregorianQuarterName | GregorianMonthBeginDate | GregorianMonthEndDate
其中GregorianQuarterName
是nvarchar
用字符串命名季度格式“FY%Y-答疑q”和GregorianMonthBeginDate
和GregorianMonthEndDate
是datetime
对象。第二个表,QuarterlyRevenueData
,保存的信息需要查询和具有格式:
Fiscal_Quarter | Product | Revenue
其中Fiscal_Quarter
具有相同的格式为GregorianQuarterName
。我只想返回当前季度或之前的第二个表中的值。我已经想通了如何将当前季度从使用第一表返回:
SELECT QDMap.GregorianQuarterName AS most_recent_quarter
FROM QuarterDateMapping QDMap
WHERE QDMap.GregorianMonthBeginDate <= GetDate()
AND QDMap.GregorianMonthEndDate >= GetDate()
成功地返回当前季度(FY17-Q1)。我遇到的困难是试图找出如何使用这个输出来查询第二个表。我曾尝试:
;WITH QuarterData As
(
SELECT QDMap.GregorianQuarterName AS most_recent_quarter
FROM QuarterDateMapping QDMap
WHERE QDMap.GregorianMonthBeginDate <= GetDate()
AND QDMap.GregorianMonthEndDate >= GetDate()
)
SELECT * FROM QuarterlyRevenueData revdata
WHERE revdata.Fiscal_Quarter <= QuarterData.most_recent_quarter
然而,这给我的错误:
Msg 4104, Level 16, State 1, Line 9
The multi-part identifier "QuarterData.most_recent_quarter" could not be bound.
当我运行相同的查询如上,但硬编码的季度:
SELECT * FROM QuarterlyRevenueData revdata
WHERE revdata.Fiscal_Quarter <= 'FY17-Q1'
它运行如预期的那样,并返回我想要的数据,但我希望我的查询能够自动更新。
谢谢你的帮助。让我知道如果我的问题需要更多信息或更好的格式,这是我的第一个SQL问题。
这大部分工作,但我需要从'SELECT'语句中删除'QDM.GregorianQuarterName,QDM.GregorianMonthBeginDate,QDM.GregorianMonthEndDate',以便获取与筛选表格相同的数据。由于输出包含3个额外的列,并且每一行上重复出现'QuarterDateMapping'的当前季度的数据。 – Barker