-1

I am trying to see 2 conditional columns using the WHERE clause from 1 column.

For example:

I have a dataset where I have a long list of calls. I would like to see two different columns where the first column shows a count of all those calls who are equal or longer that 0 seconds and a second column that shows a count of all those calls that are equal or longer to 120 seconds.

That is my first query:

SELECT distinct year(date) Year,  monthname(date) as Month, count(calls) Leads
FROM database.calls
where duration >= 120
and year(date) = 2022
group by month(date)
order by max(date); 

second query: (The only difference it's on the 3rd line where duration is equal to 0)

SELECT distinct year(date) Year,  monthname(date) as Month, count(calls) Leads
FROM database.calls
where duration >= 0
and year(date) = 2022
group by month(date)
order by max(date); 

Expected Result:

Year Month Calls(0sec) Calls(120sec)
2022 January 654 521
2022 February 895 465
2022 March 562 321
Shadow
  • 33,525
  • 10
  • 51
  • 64

1 Answers1

2

For obtaining conditional sums you can use conditional aggregation: specify a condition inside your aggregate function, so that it aggregates only the eligible values.

SELECT YEAR(date)                    AS Year_,  
       MONTHNAME(date)               AS Month_, 
       SUM(IF(duration >   0, 1, 0)) AS Calls0Sec,
       SUM(IF(duration > 120, 1, 0)) AS Calls120Sec
FROM database.calls
WHERE YEAR(date) = 2022
GROUP BY YEAR(date), MONTHNAME(date)
ORDER BY MAX(date); 

Note: you need to add every selected and non-aggregated field inside the GROUP BY clause, otherwise you can expect either DBMS errors or wrong data.

lemon
  • 14,875
  • 6
  • 18
  • 38
  • Thank you for your respond. Could you please tell me what the logic is on the 3rd and 4th line where you put 0,1,0 and 120,1,0 – Leonardo Urbiola Dec 14 '22 at 21:25
  • 1
    The basic IF construct works like this: `IF (condition, if true then, if false then)`. First field is a condition, or in general any function that outputs a boolean value. If that condition evaluates to true, second field is considered, otherwise third. – lemon Dec 14 '22 at 21:28