SQL查询返回超过1行 - 需要1行

时间:2010-11-06 20:23:28

标签: asp.net sql sql-server

我目前有以下SQL查询:

SELECT
  con_Content,
  cot_Name,
  pag_Name
FROM 
  [Page]
  inner join [Content] on con_PageID = pag_ID
  inner join [ContentType] on cot_ID = con_TypeID
WHERE 
  pag_URL = 'tour'

返回多行,如下面的屏幕截图所示:

http://i.stack.imgur.com/2GbHi.gif

我真的需要这个查询返回1行,其他列名称为'LeftColumn','RightColumn','MainContent',这些列的值为'con_content'。

我的SQL现在不是很好。

先谢谢。

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

如果你说每个页面都有左,右和&amp;通过向页面表添加左,右和中间字段,可以使中间内容更简单。否则,就个人而言,我会在应用程序中处理转换。