2

我有一个如下所示的选择查询:

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, 

我需要在不使用函数或声明变量的情况下去掉最后一个逗号,就在查询中。那可能吗?提前感谢您的回答。

4

3 回答 3

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, '') 

祝你好运。

于 2013-02-11T23:09:06.640 回答
5

您始终可以使用以下使用Left()and 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
于 2013-02-11T23:09:15.730 回答
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('')

基本上添加一个逗号,除非它是结果集的最后一条记录。

于 2015-02-13T23:21:11.677 回答