GROUP BY SQL QUERY SOME DATA ROWS AS HEADER

Madhu P 21 Reputation points
2021-02-04T08:27:32.667+00:00

Hi,

My data like below:

ID Name class score


1 P 1 20

2 P 1 20

3 A 2 10

3 A 2 20

Now I need data like below in Excel :
Name as group by
class range means like below

P
1
ID sum_score


1 20
2 20

A
2
ID sum_score


3 30

Could you please any help..,

Thanks

Developer technologies Transact-SQL
{count} votes

3 answers

Sort by: Most helpful
  1. EchoLiu-MSFT 14,621 Reputation points
    2021-02-04T08:45:20.35+00:00

    Hi @Madhu P ,

    Welcome to the Microsoft TSQL Q&A Forum!

    Please refer to:

        CREATE TABLE #test (ID int, Name char(15), class int, score int)  
        INSERT INTO #test VALUES(1,'P',1,20),(2,'P',1,20),(3,'A',2,10),(3,'A',2,20)  
          
        SELECT Name,class,ID, sum(score) sum_score  
        FROM #test  
        GROUP BY Name,class,ID  
        ORDER BY Name DESC  
    

    Outout:
    63942-image.png

    If you have any question, please feel free to let me know.
    If the response is helpful, please click "Accept Answer" and upvote it.

    Best Regards
    Echo


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  2. Madhu P 21 Reputation points
    2021-02-04T08:59:29.52+00:00

    Yes, good but I need like below
    Name(which has group by) as Top row remain empty rows
    class (which has group by) as Top row remain empty rows
    above group related IDs records
    No need to write Header , I need records as per image - please check image

    63972-image.png

    0 comments No comments

  3. EchoLiu-MSFT 14,621 Reputation points
    2021-02-04T09:17:22.16+00:00

    The data in the same column needs to have the same data type. The name column is a string, which is different from the class column in data type and cannot be placed in the same column.

    Does the following output meet your needs?

        SELECT DISTINCT Name,'' class,'' ID,'' sum_score FROM #test  
        UNION ALL  
        SELECT DISTINCT '', class,'' ,'' FROM #test  
        UNION ALL  
        SELECT Name,class,ID, sum(score) sum_score  
        FROM #test  
        GROUP BY Name,class,ID  
        ORDER BY Name DESC  
    

    Output:
    63991-image.png

    Or:

    SELECT DISTINCT Name,'' class,'' ID,'' sum_score FROM #test  
    UNION ALL  
    SELECT DISTINCT Name,class,'' ID,'' sum_score FROM #test  
    UNION ALL  
    SELECT Name,class,ID, sum(score) sum_score  
    FROM #test  
    GROUP BY Name,class,ID  
    ORDER BY Name DESC  
    

    Output:
    63992-image.png

    Echo


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.