MainframeSupports
tip week 46/2010:

A while ago one of my colleagues asked me if it is possible to make partial sums. Instantly I got an idea. Normally I use GROUP BY to create partial sums and partial counts, but you are able to do it in another way. Imagine that you want to count the number of domestic and foreign customers. In your customer table you have a column called COUNTRYCODE which contains the two letter ISO abbreviation for the home country of the customer. Such a count splittet between domestic and foreign customers is actually quite difficult to make using SQL and GROUP BY. Either you must must make a UNION where the first part counts domestic customers and the other part counts foreign customers. But you can do it without UNION like this (domestic country set to DK for Denmark):

SELECT SUM(CASE COUNTRYCODE WHEN 'DK' THEN 1 ELSE 0 END) AS DOMESTIC
     , SUM(CASE COUNTRYCODE WHEN 'DK' THEN 0 ELSE 1 END) AS FOREIGN
FROM CUSTOMERTABLE

Using the same technique it is possible to create partial sums within groups. Imagine a company that sells goods via the internet and in shops. Now the company wants to find the turnover for different groups of goods totally, for the internet and for the shops. You can do it like this:

SELECT ARTICLEGROUP, SUM(TURNOVER) AS TOTAL
     , SUM(CASE CHANNEL WHEN 'SHOP' THEN TURNOVER ELSE 0 END) AS SHOP
     , SUM(CASE CHANNEL WHEN 'INTERNET' THEN TURNOVER ELSE 0 END) AS INTERNET
FROM SALESTABLE
GROUP BY ARTICLEGROUP

Please noitice that the existance of other sales channels than SHOP and INTERNET will make the value of TOTAL larger than the value of SHOP + INTERNET provided that there has been any turnover in the other sales channels for the ARTICLEGROUP. I hope these two examples will give you inspiration to use CASE combined with SUM for problems that are relevant for you.

Previous tip in english        Sidste danske tip        Tip list