我有一个选择查询,如下所示:
SELECT
ROW_NUMBER() OVER (ORDER BY T.TitleId) as Row,
T.TitleId as TitleID,
T.TitleSort as TitleName,
TT.Description as TitleType,
TS.Description as TitleOrigin,
--get genres
(select Genre.Description + ', ' from Genre where GenreId IN
(Select GenreId from TitleGenre WHERE TitleId = T.TitleId)
group by Genre.Description for xml path('')) AS Genres, ....
此代码有效,但我无法找到摆脱最后一个逗号的方法。这是返回行的外观:
Action, Drama, Romance,
我需要在不使用函数或声明变量的情况下删除最后一个逗号,就在查询中。那可能吗?提前感谢您的回答。
答案 0 :(得分:9)
这样的东西应该接近 - 基本上将逗号移到开头,然后用STUFF删除它:
STUFF(
(
select ', ' + Genre.Description from Genre where GenreId IN
(Select GenreId from TitleGenre WHERE TitleId = T.TitleId)
group by Genre.Description for xml path('')
), 1, 2, '')
祝你好运。
答案 1 :(得分:5)
您始终可以使用以下使用Left()
和Len()
:
select *,
left(Genres, len(Genres)-1) as Genres
from
(
SELECT
ROW_NUMBER() OVER (ORDER BY T.TitleId) as Row,
T.TitleId as TitleID,
T.TitleSort as TitleName,
TT.Description as TitleType,
TS.Description as TitleOrigin,
--get genres
(select Genre.Description + ', ' from Genre where GenreId IN
(Select GenreId from TitleGenre WHERE TitleId = T.TitleId)
group by Genre.Description for xml path('')) AS Genres, ....
) src
答案 2 :(得分:0)
我已使用窗口函数执行类似下面的操作,可选择插入逗号。
SELECT
c.Name +
CASE WHEN
ROW_NUMBER() OVER (PARTITION BY t.Name ORDER BY c.Name DESC)
<>
COUNT(t.name) OVER (PARTITION BY t.Name) then ',' else '' END
FROM sys.tables t
INNER JOIN sys.columns c
on t.Object_id = c.Object_id
FOR XML PATH('')
除非它是结果集的最后一条记录,否则基本上添加一个逗号。