SQL Server Combine two columns and aggregate into one value

u3r8eeie  于 2023-06-21  发布在  其他
关注(0)|答案(2)|浏览(135)

Combine two columns in SQL Server: one column has varchar values and other column has int values.

.

This is the code I have used to get the result

Trying to combine two columns: one column is varchar and another one is int.

I'm trying to combine learningareas and Noramlyearlevel columns.

This is the actual query.

select distinct v.StaffPreferredName, v.StaffSurname, v.StaffOccupEmail, 
l.learningareacode as 'Learning Areas',
sc.NormalYearLevel as 'NormalYearLevel'
from vstaffDescription'

And I'm trying to get the result output like this


.

I tried this code,

I got the output as,

Alexander   Scott   Alex.Scott@pegs.vic.edu.au  Geography: 8, Geography: 8, Geography: 8, Politics: 10, Politics: 10.

Please guide me to get the required output.

Thanks

wfauudbj

wfauudbj1#

Please avoid images when forming questions - and also do include the complete query you have tried (it seems you omitted some parts). In essence what you want to do is remove the unwanted repetition of data before you use string_agg e.g:

SELECT
      derived.StaffPreferredName
    , derived.StaffSurname
    , derived.StaffOccupEmail
    , STRING_AGG(serived.learningAreaYearLevel, ',') WITHIN GROUP ( ORDER BY learningAreaYearLevel ) AS learningAreaYearLevel
FROM (
    SELECT DISTINCT
          v.StaffPreferredName
        , v.StaffSurname
        , v.StaffOccupEmail
        , CONCAT (l.learningareacode , ' ' , sc.NormalYearLevel) AS learningAreaYearLevel
    FROM vstaffDescription AS v
    INNER JOIN mystery_table1 AS l ON v.x = l.y
    INNER JOIN mystery_table2 AS sc ON v.x = sc.y
    ) AS derived
GROUP BY
      derived.StaffPreferredName
    , derived.StaffSurname
    , derived.StaffOccupEmail

You will need to repair the missing table references and joins.

t2a7ltrp

t2a7ltrp2#

This is the full code I have used.

SELECT v.StaffPreferredName, v.StaffSurname, v.StaffOccupEmail,
STRING_AGG(CONCAT(l.Description, ': ', CAST(sc.NormalYearLevel AS VARCHAR)), ', 
') AS 'Learning Area Description' FROM vstaff v
JOIN SubjectClassStaff scf ON v.StaffID = scf.StaffID
JOIN SubjectClasses sc ON sc.FileType = scf.FileType
AND sc.FileYear = scf.FileYear
AND sc.FileSemester = scf.FileSemester
AND sc.ClassCode = scf.ClassCode
AND sc.ClassCampus = scf.ClassCampus
JOIN LearningAreas AS l ON l.FileType = sc.FileType
AND l.FileType = sc.FileType
AND sc.LearningAreaCode = l.LearningAreaCode
WHERE
sc.FileType = 'a'
AND sc.FileSemester = 3
AND sc.FileYear = 2023
AND l.LearningAreaCode <> ' '
AND sc.NormalYearLevel IS NOT NULL
GROUP BY
v.StaffPreferredName,
v.StaffSurname,
v.StaffOccupEmail
ORDER BY
v.StaffPreferredName;

相关问题