I have a table called traffic shown below. I have to write a query which list all the protocols for which incoming traffic is higher than outgoing. The result should be in this format – protocol, traffic_in, traffic_out and sorted in ascending by protocol.
Query I wrote was,
select
protocol
, sum(traffic_in)
, sum(traffic_out)
from traffic
group by protocol
order by protocol asc;
but it did not work. I know I am missing something but couldn’t figure out. Could someone please help with the query?
3
Answers
You are on the right track with the aggregation query. You did
sum
the total traffic in both directions for each protocl; all that is left to do is compare those aggregated values.For this, you would use a
HAVING
clause ; that’s a specialWHERE
clause, but unlike the latter it is allowed to operate on aggregate functions. So:Side note:
asc
is the default sort order.If you want to know if the the comlete sum is higheer you can use
HAVING
We can use this query which uses sign() function (if traffic_in > traffic_out, then traffic_in-traffic_out = positive value and sign returns +1 and order by 1 to display all in ascending of protocol
select protocol, traffic_in, traffic_out from traffic where sign(traffic_in-traffic_out)=1 order by 1;