下午,为新手问题道歉,但我使用临时表编写了以下SQL代码,我想将它用作视图,我确信它可以在不使用临时表的情况下编写,但如果有人可以提供帮助我并指出我正确的方向,我需要做什么,我将不胜感激。 SQL Server 2008 R2
select R.Code, R.Name, R.[Department Code], R.[Line Role]
into #first
from [Employment Role] R
select R.Code, R.Name, R.[Department Code], R.[Line Role]
into #second
from [Employment Role] R
select R.Code, R.Name, R.[Department Code], R.[Line Role]
into #senior
from [Employment Role] R
select emp.[First Name], emp.[Last Name], f.Name AS [Employee Job Title], f.[Department Code] as [Employee Department],
s.Name as [Manager Job Title], s.[Department Code] as [Manager Department], snr.Name as [Senior Manager Job Title],
snr.[Department Code] as [Senior Manager Department]
from #first f
join #second s on f.[Line Role] = s.Code
join #senior snr on s.[Line Role] = snr.Code
join [Employee] Emp on Emp.[Role Name] = f.Name
drop table #first
drop table #second
drop table #senior
答案 0 :(得分:1)
这看起来只使用别名,而不使用CTE。
select emp.[First Name], emp.[Last Name], f.Name AS [Employee Job Title],
f.[Department Code] as [Employee Department],
s.Name as [Manager Job Title],
s.[Department Code] as [Manager Department],
snr.Name as [Senior Manager Job Title],
snr.[Department Code] as [Senior Manager Department]
from [Employment Role] f
join [Employment Role] s on f.[Line Role] = s.Code
join [Employment Role] snr on s.[Line Role] = snr.Code
join [Employee] Emp on Emp.[Role Name] = f.Name
答案 1 :(得分:0)
WITH first_CTE (Code, Name, [Department Code], [Line Role])
AS
(
select R.Code, R.Name, R.[Department Code], R.[Line Role]
from [Employment Role] R
), second_CTE (Code, Name, [Department Code], [Line Role])
AS
(
select R.Code, R.Name, R.[Department Code], R.[Line Role]
from [Employment Role] R
)
select *
from first_CTE join second_CTE ...
答案 2 :(得分:0)
看起来您的临时表都具有相同的数据,因此您只需使用一个cte并将其连接到自身:
WITH cte
AS ( SELECT R.Code ,
R.Name ,
R.[Department Code] ,
R.[Line Role]
FROM [Employment Role] R
)
SELECT emp.[First Name] ,
emp.[Last Name] ,
f.Name AS [Employee Job Title] ,
f.[Department Code] AS [Employee Department] ,
s.Name AS [Manager Job Title] ,
s.[Department Code] AS [Manager Department] ,
snr.Name AS [Senior Manager Job Title] ,
snr.[Department Code] AS [Senior Manager Department]
FROM cte f
INNER JOIN cte s ON f.[Line Role] = s.Code
INNER JOIN cte snr ON s.[Line Role] = snr.Code
INNER JOIN [Employee] Emp ON Emp.[Role Name] = f.Name