sunpack
sunpack

Reputation: 95

Grouping rows with each different row has header row SQL Server

I am trying to group some data in SQL Server. However not sure if there is a query that can do this. Below is the original data

Type    Number      Date            Result
Car     6664441111  Feb 22 2016     IVR Detected
Car     6664441111  Feb 22 2016     Answered
Lab     5552221111  Feb 22 2016     No Answer
Lab     5552221111  Feb 22 2016     Hangup
Lab     5552221111  Feb 22 2016     Answered

I would like to know a query that can do this:

Type    Number      Date            Result    
Car     6664441111  Feb 22 2016     IVR Detected
        6664441111  Feb 22 2016     Answered
Lab     5552221111  Feb 22 2016     No Answer
        5552221111  Feb 22 2016     Hangup
        5552221111  Feb 22 2016     Answered

I am using SQL Server. Thank you in advance

Upvotes: 1

Views: 295

Answers (1)

Kamil Gosciminski
Kamil Gosciminski

Reputation: 17177

Assuimg your data is sorted already and doesn't need to be sorted to make your logic happen you could use a row_number window function:

select
  CASE WHEN row_num = 1 THEN type END AS type, number, date, result
from (
  select type, number, date, result, row_number() over (partition by type) AS row_num
  from t
  ) x

If you need to order your data to appear like in your example, you need to add order by within window function.

Upvotes: 1

Related Questions