SQL Server SQL查询返回1行以上-需要1行

okxuctiv  于 2022-12-26  发布在  其他
关注(0)|答案(2)|浏览(193)

我目前有以下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现在不是很好。

xtupzzrd

xtupzzrd1#

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

qni6mghb2#

如果你说每个页面都有左、右和中间的内容,你可以通过在页面表中添加左、右和中间字段来简化它。否则,我个人会在应用程序中处理转换。

相关问题