下面的動態查詢似乎工作:
declare @columnlist nvarchar(4000)
select @columnlist = IsNull(@columnlist + ', ', '') + '[' + PositionName + ']'
from #Position
declare @query nvarchar(4000)
select @query = '
select *
from (
select CategoryId, CategoryName, PositionName,
IsNull(COrder,0) as COrder
from #Position p
cross join #Category c
left join #CategoryPosition cp
on cp.pid = p.PositionId
and cp.cid = c.CategoryId
) pv
PIVOT (max(COrder) FOR PositionName in (' + @columnlist + ')) as Y
ORDER BY CategoryId, CategoryName
'
exec sp_executesql @query
一些澄清:
- 的@columnlist包含dymamic字段列表,從持倉表
- 的交叉連接建立創建所有類別和所有位置的列表
- 左連接查找相應的COrder
- MAX()選擇每個類別+位置最高CORDER,如果有多於一個的
- PIVOT()打開的各種PositionNames成單獨的列
P.S.我的表名以#開頭,因爲我將它們創建爲臨時表。刪除#以引用永久表。
P.S.2。如果有人想在此嘗試他的手,這裏是一個腳本,在這個問題上,以創建表:
set nocount on
if object_id('tempdb..#Category') is not null drop table #Category
create table #Category (
CategoryId int identity,
CategoryName varchar(50)
)
insert into #Category (CategoryName) values ('Home')
insert into #Category (CategoryName) values ('Contact')
insert into #Category (CategoryName) values ('About')
--insert into #Category (CategoryName) values ('News')
if object_id('tempdb..#Position') is not null drop table #Position
create table #Position (
PositionID int identity,
PositionName varchar(50)
)
insert into #Position (PositionName) values ('Main menu')
insert into #Position (PositionName) values ('Left menu')
insert into #Position (PositionName) values ('Right menu')
--insert into #Position (PositionName) values ('Bottom menu')
if object_id('tempdb..#CategoryPosition') is not null
drop table #CategoryPosition
create table #CategoryPosition (
CPID int identity,
CID int,
PID int,
COrder int
)
insert into #CategoryPosition (CID, PID, COrder) values (1,1,1)
insert into #CategoryPosition (CID, PID, COrder) values (1,2,2)
insert into #CategoryPosition (CID, PID, COrder) values (1,3,3)
insert into #CategoryPosition (CID, PID, COrder) values (2,1,4)
insert into #CategoryPosition (CID, PID, COrder) values (2,3,5)
你可以**解釋**你想完成什麼?剛剛列出一堆表格真的沒有多大幫助...... – 2009-05-24 17:09:57