读书人

inner join和case能一起使用吗?解决方

发布时间: 2012-01-20 18:53:53 作者: rapoo

inner join和case能一起使用吗?
Select P.*,T.Name From PartsCTE as P
inner join
CASE TypeId
WHEN 1 THEN [Regional]
WHEN 2 THEN [Tours]
end as T
on T.ID=P.ObjectId

Regional,Tours为表名

[解决办法]
当然可以,但是用法不对
[解决办法]
Select
P.*,
case TypeId
when 1 then (select Name from [Regional] where ID=P.ObjectId)
when 2 then (select Name from [Tours] where ID=P.ObjectId)
end as Name
From
PartsCTE as P
[解决办法]
还可以用union

select P.*,T.Name from PartsCTE P,[Regional] T where T.ID=P.ObjectId
union all
select P.*,T.Name from PartsCTE P,[Tours] T where T.ID=P.ObjectId
[解决办法]
--这样写
Select P.*,T.Name
From PartsCTE as P inner join
(
select 1 as sort,id,name from [Regional]
union
select 2 as sort,id,name from [Tours]
)t
on T.ID=P.ObjectId and t.sort = p.typeid

读书人网 >SQL Server

热点推荐