我有以下查询:
WITH Calender AS
(
SELECT @FromDate AS CalanderDate
UNION ALL
SELECT CalanderDate + 1 FROM Calender
WHERE CalanderDate + 1 <= @ToDate
)
INSERT INTO #C
SELECT [Date] = CONVERT(VARCHAR(10),CalanderDate,25)
, case [dbo].[CalculateNumericWeekCode] (4, CalanderDate)
when 1 then 'A'
when 2 then 'B'
when 3 then 'C'
when 4 then 'D'
end
, TT.Name
, 'Green'
, 'Green'
, FREQ.pageid
,''
FROM Calender,
TransportType AS TT INNER JOIN #F AS FREQ ON FREQ.TransportTypeID = TT.TransportTypeId
WHERE TT.TransportTypeID = @TransportTypeID
UNION
SELECT [Date] = CONVERT(VARCHAR(10),CalanderDate,25)
, case [dbo].[CalculateNumericWeekCode] (4, CalanderDate)
when 1 then 'A'
when 2 then 'B'
when 3 then 'C'
when 4 then 'D'
end
, TT.Name
, Case INC.incidentstatusid
when 6 -- Approved
then 'Blue'
else
''
END
, 'Green'
, FREQ.pageid
,''
FROM Calender,
TransportType AS TT INNER JOIN #F AS FREQ ON FREQ.TransportTypeID = TT.TransportTypeId
INNER JOIN [Incident] AS INC on FREQ.Task = INC.Task AND FREQ.Contract = INC.Contract AND CalanderDate = INC.[EstimatedCompletionStamp]
INNER JOIN [IncidentStatus] AS INCSTAT ON INCSTAT.IncidentStatusID = INC.IncidentStatusID
INNER JOIN [IncidentSubType] AS INCSTYP ON INCSTYP.incidentsubtypeid = INC.IncidentSubTypeID and INC.IncidentSubTypeID in (20,21,22,23) and INC.TransportTypeId = TT.TransportTypeID
我的#C-table声明如下:
CREATE TABLE #C
(
DateOfTransport DateTime not null,
WeekCode varchar(1) NOT NULL,
[TransportType] varchar(25) NULL,
[CSDColor] varchar(10) not null,
[WWWColor] varchar(10) not null,
[PageID] int not null,
[ToolTip] varchar(250) null
)
现在,当我运行查询时,收到消息:无效的列名'CalanderDate'。
当我删除UNION它工作正常。 但我确实需要不同表之间的联合。
任何人都可以帮助我吗?
答案 0 :(得分:2)
我想我发现了这个问题:
正如我所怀疑的,它是由你的混合风格引起的:
此on
子句无效on FREQ.Task = INC.Task AND FREQ.Contract = INC.Contract AND CalanderDate = INC.[EstimatedCompletionStamp]
,因为您在calander
上使用隐式联接。
我认为这应该有效:
SELECT [Date] = CONVERT(VARCHAR(10),CalanderDate,25)
, case [dbo].[CalculateNumericWeekCode] (4, CalanderDate)
when 1 then 'A'
when 2 then 'B'
when 3 then 'C'
when 4 then 'D'
end
, TT.Name
, Case INC.incidentstatusid
when 6 -- Approved
then 'Blue'
else
''
END
, 'Green'
, FREQ.pageid
,''
FROM TransportType AS TT
INNER JOIN #F AS FREQ ON FREQ.TransportTypeID = TT.TransportTypeId
INNER JOIN [Incident] AS INC on FREQ.Task = INC.Task AND FREQ.Contract = INC.Contract
INNER JOIN Calender ON CalanderDate = INC.[EstimatedCompletionStamp]
INNER JOIN [IncidentStatus] AS INCSTAT ON INCSTAT.IncidentStatusID = INC.IncidentStatusID
INNER JOIN [IncidentSubType] AS INCSTYP ON INCSTYP.incidentsubtypeid = INC.IncidentSubTypeID and INC.IncidentSubTypeID in (20,21,22,23) and INC.TransportTypeId = TT.TransportTypeID