SQL STUFF not working, why?

为君一笑 提交于 2019-12-24 07:28:32

问题


I did lot of querys on Oracle, and now I'm working with SQL Server. I saw the way of use similar function like listagg from oracle in sql server (stuff).

    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  

The sintax its correct, but the result not.

The goal is have for example for the 2 top rows, the result as 1 - RH, Planta Brasilia

Where is the problem ?


回答1:


You should distinct id_question first and inner join to tb_departament like this

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



回答2:


Missing group by 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



回答3:


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
-----------------------------------------------



回答4:


Thanks to help guys, here the final sql works fine:

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


来源:https://stackoverflow.com/questions/44146920/sql-stuff-not-working-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!