   13:33

# CASE statement page 3

Let's consider a few more examples.

Determine number of trips from Rostov to Moscow, and number of trips to other towns (not to Moscow).

Here we can use additional computed column for grouping by it.  Console
`SELECT flag, COUNT(*) qty FROM (SELECT CASE WHEN town_to ='Moscow' THEN 'Moscow' ELSE 'Other' END flagFROM TripWHERE town_from='Rostov') X GROUP BY flag;`

flag    qty
Moscow  4
Other    2

Determine total number of trips from Rostov, and number of trips from Rostov to towns other than Moscow.

This problem requires to do grouping by two sets also, but now one set is a subset of another one. So exactly the same approach based on computed column is not fit here. In the previous task we had two non-intersecting sets to do grouping for each.

To solve this task we can calculate count over total set and use subquery to calculate the count over subset (second referense to a table), or we can use CASE statement in the conjunction  with aggregate function to avoid second reading of a table. Let's check the estimation of optimizer for these two variants.

### Use of subquery  Console
`SELECT COUNT(*) total, (SELECT COUNT(*) FROM Trip WHERE town_from='Rostov' AND town_to <> 'Moscow') non_moscowFROM TripWHERE town_from='Rostov';`

### Use of CASE with aggregate function  Console
`SELECT COUNT(*) total_qty,  SUM(CASE WHEN town_to <>'Moscow' THEN 1 ELSE 0 END) non_moscowFROM TripWHERE town_from='Rostov';`

The result will be the same naturally:

total   non_moscow
6    2

but the cost of the second query, as was expected,  is twice as less than of the first one.

You can compare the real run time of these queries on sufficient large amount of data.

The second variant can be rewritten in more short form with use of NULLIF function:  Console
`SELECT COUNT(*) total_qty,  COUNT(NULLIF(town_to, 'Moscow')) non_moscowFROM TripWHERE town_from='Rostov';`

NULLIF function returns NULL, if its arguments are equal, or the first one otherwise.

The solution exploits the fact that the aggregate functions don't take into account NULL values which arise in argument of COUNT function when the landing town is 'Moscow'.

 Pages 1 2 3 4
Tags
The book was updated
month ago
обменять с альфа клик