Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this possible with SQL Server

Tags:

sql

sql-server

I have a table which has events and the day they occurred:

Table 'Events':

Name  Day
-----------
A     1
B     2
A     2
B     3

I need output columns to be a date range based on query input with rows being which event happened on the day so:

Desired output:

Day-1 Day-2 Day-3
-----------------
A     A     -
-     B     B

If this is possible can anyone give me a sample query that could generate this output based on a date range. There are all sorts of I have no clue how to even approach this issues here like an unknown number of columns.

like image 649
MikeO Avatar asked Apr 08 '26 13:04

MikeO


1 Answers

You can use conditional aggregation:

select max(case when day = 1 then name end) as day_1,
       max(case when day = 2 then name end) as day_2,
       max(case when day = 3 then name end) as day_3       
from t
group by name;

Note: This returns NULL rather than -. I think NULL makes more sense.

like image 154
Gordon Linoff Avatar answered Apr 11 '26 04:04

Gordon Linoff