将多行转换为一行 - SQL
Convert Multiple Rows into One - SQL
我试图让 'test' 列在同一行中。我正在使用 Stuff()
但是,似乎 'test' 列正在遍历所有 qID
我错过了什么?
SELECT DISTINCT qID,
STUFF((
select ',' + B.text
from tbl B
where B.qID=qID
order by B.text
for xml path('')
),1,1,'') as test
FROM tbl
WHERE qID in (2258060,2296222)
GROUP BY qID
您在 table
上缺少别名
- 条件B.qID=qID returns 始终为真,就好像 1=1,它什么也没做。它类似于 B.qID=B.qID.
通过使用别名:
SELECT DISTINCT qID,
STUFF((
select ',' + B.text
from tbl B
where B.qID=A.qID
order by B.text
for xml path('')
),1,1,'') as test
FROM tbl A
WHERE qID in (2258060,2296222)
GROUP BY qID
也可以在外部查询中不使用别名,使用 table 名称本身。
SELECT DISTINCT qID,
STUFF((
select ',' + B.text
from tbl B
where B.qID=tbl.qID --Table name before qid here
order by B.text
for xml path('')
),1,1,'') as test
FROM tbl
WHERE qID in (2258060,2296222)
GROUP BY qID
我试图让 'test' 列在同一行中。我正在使用 Stuff()
但是,似乎 'test' 列正在遍历所有 qID
我错过了什么?
SELECT DISTINCT qID,
STUFF((
select ',' + B.text
from tbl B
where B.qID=qID
order by B.text
for xml path('')
),1,1,'') as test
FROM tbl
WHERE qID in (2258060,2296222)
GROUP BY qID
您在 table
上缺少别名- 条件B.qID=qID returns 始终为真,就好像 1=1,它什么也没做。它类似于 B.qID=B.qID.
通过使用别名:
SELECT DISTINCT qID,
STUFF((
select ',' + B.text
from tbl B
where B.qID=A.qID
order by B.text
for xml path('')
),1,1,'') as test
FROM tbl A
WHERE qID in (2258060,2296222)
GROUP BY qID
也可以在外部查询中不使用别名,使用 table 名称本身。
SELECT DISTINCT qID,
STUFF((
select ',' + B.text
from tbl B
where B.qID=tbl.qID --Table name before qid here
order by B.text
for xml path('')
),1,1,'') as test
FROM tbl
WHERE qID in (2258060,2296222)
GROUP BY qID