正如@Donnie所說,聽起來你想要做一個關鍵。如果這是SQL Server 2005或更高版本:
with Page (con_Content, cot_Name, pag_Name)
as
(
select '<p>this could be the left content</p>', 'LeftColumn', 'Tour'
union
select '<p>this could be the right content</p>', 'RightColumn', 'Tour'
union
select '<p>main content</p>', 'MainContent', 'Tour'
)
select pag_Name, LeftColumn, RightColumn, MainContent
from [Page]
pivot
(
min(con_Content)
for cot_Name in (LeftColumn, RightColumn, MainContent)
) as PivotTable
where pag_Name = 'Tour'
,如果這是沒有的SQL Server 2005+:
/* with cte defined as above */
select pag_Name,
max(case cot_Name when 'LeftColumn' then con_Content else '' end) LeftColumn,
max(case cot_Name when 'RightColumn' then con_Content else '' end) RightColumn,
max(case cot_Name when 'MainContent' then con_Content else '' end) MainContent
from [Page]
where pag_Name = 'Tour'
group by pag_Name
編輯
如果一個沒有相應cot_Name
值字段在數據透視表中,該查詢仍將執行並返回該字段的null
。
例如,試試這個:
with Page (con_Content, cot_Name, pag_Name)
as
(
select '<p>this could be the left content</p>', 'LeftColumn', 'Tour'
union
select '<p>main content</p>', 'MainContent', 'Tour'
)
select pag_Name, LeftColumn, RightColumn, MainContent
from [Page]
pivot
(
min(con_Content)
for cot_Name in (LeftColumn, RightColumn, MainContent)
) as PivotTable
where pag_Name = 'Tour'
所以你的情況,你可以包括每一個你感興趣的價值,只是檢查null
看pag_Name
是否有該cot_Name
任何內容:
/* using cte as defined above */
select pag_Name, LeftColumn, RightColumn, MainContent, MoreContent_1, MoreContent_2 /* etc. */
from [Page]
pivot
(
min(con_Content)
for cot_Name in (LeftColumn, RightColumn, MainContent, MoreContent_1, MoreContent_2)
) as PivotTable
where pag_Name = 'Tour'
查找'pivot'關鍵字。 msdn頁面(在本評論結尾處)有很好的例子,可以幫助你:http://msdn.microsoft.com/en-us/library/ms177410.aspx – Donnie 2010-11-06 20:31:15