日期:2014-05-18  浏览次数:20593 次

求一sql 语句(在线等)
create   table   #Market

(
Id   int   ,
Name   varchar(10)  
)

insert   into   #Market(Id   ,   Name)   values( '1 ', 'Shanghai ')
insert   into   #Market(Id   ,   Name)   values( '2 ', 'Beijing ')
insert   into   #Market(Id   ,   Name)   values( '3 ', 'Guangzhou ')
insert   into   #Market(Id   ,   Name)   values( '4 ', 'Yangzhou ')

create   table   #Pannel
(
Id   int   ,
Name   varchar(50)  
)

insert   into   #Pannel(Id   ,   Name)   values( '10 ', 'AGB ')
insert   into   #Pannel(Id   ,   Name)   values( '20 ', 'CSM ')
insert   into   #Pannel(Id   ,   Name)   values( '30 ', 'AGB(great   city) ')


create   table   #MarketMap
(
MarketId   int,
PannelId   int
)

insert   into   #MarketMap   values(1,10)
insert   into   #MarketMap   values(1,20)
insert   into   #MarketMap   values(1,30)
insert   into   #MarketMap   values(2,10)
insert   into   #MarketMap   values(2,20)
insert   into   #MarketMap   values(2,30)
insert   into   #MarketMap   values(3,10)
insert   into   #MarketMap   values(3,20)

DROP   TABLE   #Market  
DROP   TABLE   #Pannel  
DROP   TABLE   #MarketMap  


最后要得到的结果是  
/*
itemValue displayName   AGB_10, CSM_20 AGB(great   city)_30
1 shanghai   1 1 1
2 beijing   1 1 1
3 guangzhou 1 1 0
4 yangzhou 0 0 0

*/
请问这个sql该怎么写
谢谢


------解决方案--------------------

select isnull(mm.marketid,m.id) as itemValue, m.name
,max(case when mm.pannelid = 10 then 1 else 0 end) as AGB_10
,max(case when mm.pannelid = 20 then 1 else 0 end) as CSM_20
,max(case when mm.pannelid = 30 then 1 else 0 end) as [AGB(great city)_30]
from #MarketMap mm
join #Pannel p on p.id = mm.pannelid
right join #Market m on m.id = mm.marketid
group by mm.marketid,m.name,m.id
order by itemValue
go
DROP TABLE #Market
DROP TABLE #Pannel
DROP TABLE #MarketMap

/*
itemValue name AGB_10 CSM_20 AGB(great city)_30
----------- ---------- ----------- ----------- ------------------
1 Shanghai 1 1 1
2 Beijing 1 1 1
3 Guangzhou 1 1 0
4 Yangzhou 0 0 0

(4 row(s) affected)
*/

------解决方案--------------------
create table #Market

(
Id int ,
Name varchar(10)
)

insert into #Market(Id , Name) values( '1 ', 'Shanghai ')
insert into #Market(Id , Name) values( '2 ', 'Beijing ')
insert into #Market(Id , Name) values( '3 ', 'Guangzhou ')
insert into #Market(Id , Name) values( '4 ', 'Yangzhou ')

create table #Pannel
(
Id int ,
Name varchar(50)
)

insert into #Pannel(Id , Name) values( '10 ', 'AGB ')
insert into #Pa