我在Oracle上做了很多查询,现在我正在使用SQL Server。 我在sql server(stuff)中看到了使用类似函数的方式,如来自oracle的listagg。
Select
sqd.id_question,
STUFF((Select ',' + nm_departament from tb_departament where sqd.id_departament = id_departament for xml path('')),1,1,'') nm_departements
from
tb_survey_question_departament sqd
sintax是正确的,但结果却没有。
目标是例如2个顶行,结果为1 - RH,Planta Brasilia
问题出在哪里?
答案 0 :(得分:1)
您应该先distinct id_question
,inner join
到tb_departament
这样
Select
sqd.id_question,
STUFF((
SELECT ',' + td.nm_departament
from tb_departament td
INNER JOIN tb_survey_question_departament sqd1 ON sqd1.id_departament = td.id_departament
WHERE sqd1.id_question = sqd.id_question
FOR XML PATH('')
)
,1,1,'') AS nm_departements
from
(
SELECT DISTINCT sqd.id_question
FROM tb_survey_question_departament sqd
) sqd
答案 1 :(得分:0)
id_Question错过群组...
Select
sqd.id_question,
STUFF((Select ',' + nm_departament from tb_departament where sqd.id_departament = id_departament for xml path('')),1,1,'') nm_departements
from
tb_survey_question_departament sqd
group by sqd.id_question
答案 2 :(得分:0)
CREATE TABLE tblSample (
EMPNAME VARCHAR(10)
,DEPTNAME VARCHAR(10)
,LEAVETYPE VARCHAR(20)
,TOTALLEAVE INT
);
INSERT INTO tblSample (EMPNAME, DEPTNAME, LEAVETYPE, TOTALLEAVE)
VALUES ('ANDREW','CSE','SICKLEAVE',3)
,('GEORGE','IT','CASUALLEAVE',1)
,('ANDREW','CSE','CASUALLEAVE',2)
,('GEORGE','IT','SICKLEAVE',2);
SELECT EMPNAME
,DEPTNAME
,STUFF((
SELECT ',' + LEAVETYPE + '-' + CAST(TOTALLEAVE AS VARCHAR(5))
FROM tblSample
WHERE EMPNAME = T.EMPNAME
AND DEPTNAME = T.DEPTNAME
FOR XML PATH('')
), 1, 1, '') AS LEAVETYPE
,SUM(TOTALLEAVE) AS TOTALLEAVE
FROM tblSample T
GROUP BY EMPNAME
,DEPTNAME
-----------------------------------------------
答案 3 :(得分:0)
感谢帮助人员,这里最终的sql工作正常:
Select
sqd.id_question,
que.ds_question,
STUFF((
SELECT ',' + td.nm_departament
from tb_departament td
INNER JOIN tb_survey_question_departament sqd1 ON sqd1.id_departament = td.id_departament
WHERE sqd1.id_question = sqd.id_question
FOR XML PATH('')
)
,1,1,'') AS nm_departements
from
(
SELECT DISTINCT sqd.id_question
FROM tb_survey_question_departament sqd
) sqd
inner join tb_survey_question que on sqd.id_question = que.id_question