2010-11-06 47 views
1

我现在有下面的SQL查询:SQL查询返回超过1行 - 需要1行

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

查找'pivot'关键字。 msdn页面(在本评论结尾处)有很好的例子,可以帮助你:http://msdn.microsoft.com/en-us/library/ms177410.aspx – Donnie 2010-11-06 20:31:15

回答

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' 

所以你的情况,你可以包括每一个你感兴趣的价值,只是检查nullpag_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' 
+0

几乎在那里,我唯一的问题是我不知道如果页面包含LeftColumn,RightColumn,有无论如何使查询更动态?再次感谢 – James 2010-11-07 16:54:55

+0

@James,如果'LeftColumn'或'RightColumn'没有行,它将在pivoted输出中返回NULL。查看我的编辑例子。 – 2010-11-07 18:32:12

+0

我认为它非常接近。这可能是我愚蠢的!我跑顶部的查询和它的作品却很大仍然包括: 选择“

,这可能是左边的内容

”,“LeftColumn”,“旅游” 工会 选择“

主要内容

”,“搜索Maincontent”,'游' 然后我跑了第二个查询,它不工作。对不起,如果这对你非常沮丧。你可以确认查询运行 – James 2010-11-08 20:18:17

0

如果您要说每个页面都有左侧,右侧&中间内容,您可以通过在页面表中添加左侧,右侧和中间字段来简化操作。否则,我会亲自处理应用程序中的转换。

+0

每个页面可能会有更多或更少。我想尽可能使应用程序灵活。 – James 2010-11-06 20:36:35