简体   繁体   中英

SQL Server: Modifying this query

This query gives me all the information that I need, however I'm wanting to display it differently if possible. The current result: http://i.imgur.com/BFKGFSx.jpg

DECLARE @MainHospital varchar(50)='HOSPITAL 1';
SELECT MainEmail, chkOutpatient, chkPartB
FROM SurveyPicList
WHERE MainHospital = @MainHospital
GROUP BY MainHospital, MainEmail, chkOutpatient, chkPartB

I'm trying to return 2 different list of MainEmail comma-delimited if they = "on" in chkOutpatient and chkPartB. So only 2 cells of data as a result. 1 header of chkOutpatient with a list of comma dilmeted emails that = "on", and 1 header of chkPartB with the same.

So for chkPartB, something like this? http://i.imgur.com/RFlV24Q.jpg

SELECT DISTINCT ', ' + MainEmail AS chkPartB
FROM SurveyPicList
WHERE MainHospital = @MainHospital
AND chkPartB = 'on'

Please let me know if my question is unclear or if I need to give more info.

WITH Outpatients AS (
    SELECT DISTINCT MainEmail
    FROM SurveyPicList
    WHERE MainHospital = @MainHospital
          AND chkOutpatient = 'on'
)
,OutpatientsRawCsv AS (
    SELECT (
       SELECT ',' + MainEmail
       FROM Outpatients
       FOR XML PATH('')
    ) AS Csv
)
,PartBs AS (
    SELECT DISTINCT MainEmail
    FROM SurveyPicList
    WHERE MainHospital = @MainHospital
          AND chkPartB = 'on'
)
,PartBRawCsv AS (
    SELECT (
       SELECT ',' + MainEmail
       FROM PartBs
       FOR XML PATH('')
    ) AS Csv
)
SELECT STUFF(OutpatientsRawCsv.Csv, 1, 1, '') AS OutpatientsCsv
      ,STUFF(PartBRawCsv.Csv, 1, 1, '') AS PartBCsv
FROM OutpatientsRawCsv
     CROSS JOIN PartBRawCsv

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM