SQL Server - Possible Pivot Solution?

后端 未结 1 1920
有刺的猬
有刺的猬 2020-12-04 01:33

I have a simple enough issue that has been surprisingly difficult to locate online. Perhaps I am searching on improper keywords so I wanted to stop in and ask you guys becau

相关标签:
1条回答
  • 2020-12-04 02:01

    In SQL-Server use the FOR XML Path Method:

    SELECT  Student,
            Total,
            STUFF(( SELECT  ', ' + BookID
                    FROM    MyStudies books
                    WHERE   Books.Student = MyStudies.Student
                    FOR XML PATH(''), TYPE
                    ).value('.', 'VARCHAR(MAX)'), 1, 2, '') AS Books
    FROM    (   SELECT  Student, COUNT(*) AS Total
                FROM    myStudies
                GROUP BY Student
            ) MyStudies
    

    I have previously given a full explanation of how the XML PATH Method works here. With a further improvement to my answer pointed out here

    SQL Server Fiddle


    In MySQL AND SQLite you can use the GROUP_CONCAT function:

    SELECT  Student, 
            COUNT(*) AS Total, 
            GROUP_CONCAT(BookID) AS Books
    FROM    myStudies
    GROUP BY Student
    

    MySQL Fiddle

    SQLite Fiddle


    In Postgresql you can use the ARRAY_AGG Function:

    SELECT  Student, 
            COUNT(*) AS Total, 
            ARRAY_AGG(BookID) AS Books
    FROM    myStudies
    GROUP BY Student
    

    Postgresql Fiddle


    In oracle you can use the LISTAGG Function

    SELECT  Student, 
            COUNT(*) AS Total, 
            LISTAGG(BookID, ', ') WITHIN GROUP (ORDER BY BookID) AS Books
    FROM    myStudies
    GROUP BY Student
    

    Oracle SQL Fiddle


    0 讨论(0)
提交回复
热议问题