正如@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