Search code examples
sql-serverssrs-2008reportbuilder3.0

SQL- Grouping all data for one specific ID


I am sure there is an easy solution to this, but I can't wrap my head around it. So I have a table that contains several columns:

ID, Summary, Users

However for one ID there is multiple users and each user has a different summary. All of that is fine, however the ID keeps on getting repeated for every user. I just want to show the ID once and all the data for it.

Example:

ID | Summary | Users
5  | Hi      | me 
5  | Hello   | you
5  | Stack   | him
5  | Over    | someone

What I want it to do:

ID | Summary | Users
5  | Hi      | me 
   | Hello   | you
   | Stack   | him
   | Over    | someone

So ID 5 would be only displayed as one row rather then 4 different ones. I was trying some case statements, but that doesn't help. The group by clause would require an aggregate function, which would result in a sum or a count and not the actual ID. I am kind of lost or I missed something. Any help would be appreciated. Thank you.


Solution

  • This is something which is probably best handled in your presentation layer, e.g. something like PHP or Java. But, there might be a way to do this directly from SQL Server:

    SELECT
        CASE WHEN ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Summary) = 1
             THEN CONVERT(varchar(10), ID)
             ELSE '' END AS ID_value,
        Summary,
        Users
    FROM yourTable
    ORDER BY
        ID,
        Summary;
    

    enter image description here

    Demo

    In order to make this work, there needs to be some sort of ordering by which we can say that a certain record from a group of ID values is "first," and thereby should report the ID value, while the other do not. I used ROW_NUBMER for this, and displayed the ID value for the first summary value alphabetically. Another note, I needed to cast the ID to text in the CASE expression, so that we can use empty string for the non showing ID records.