2010-11-06 87 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