Skip to content
Advertisement

Creating multiple columns from filtered values in single column in SQL

I need a bit of help I have a database that looks something like this:

enter image description here

and I would like to separate this table creating 1 column per queue and grouping the times to have a unique list as I only filter 24 hours at a time.

The expected outcome would be something like this:

enter image description here

So far the code I have tried is:

select intervals,
case when Queue = 'A' then #calls end as queueA#calls,
case when Queue = 'A' then %callsAnswered end as queueA%ans,
case when Queue = 'B' then #calls end as queueB#calls,
case when Queue = 'B' then %callsAnswered end as queueB%ans,
case when Queue = 'C' then #calls end as queueC#calls,
case when Queue = 'C' then %callsAnswered end as queueC%ans
from myTable
group by intervals
order by intervals

But I get an empty list with just the intervals so far. Could you help me, please?

Advertisement

Answer

Use aggregation. If you have only one row per time, then:

select intervals,
       max(case when Queue = 'A' then #calls end) as queueA#calls,
       max(case when Queue = 'A' then %callsAnswered end) as queueA%ans,
       max(case when Queue = 'B' then #calls end) as queueB#calls,
       max(case when Queue = 'B' then %callsAnswered) end as queueB%ans,
       max(case when Queue = 'C' then #calls end) as queueC#calls,
       max(case when Queue = 'C' then %callsAnswered end) as queueC%ans
from myTable
group by intervals
order by intervals
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement