Q:

How to do looping in SQL?

I've never attempted to loop in SQL, I have done in PHP but mainly through copying examples (although I do understand the concept).
My Question is....
I have a report where I generate headings depending on the contents of three fields: Division, Department and Branch. I create the headings manually by doing...
sum(case when Division = 'Property' and Department = 'High Value' and Branch = 'London' then Net end) as 'Prop|HighValue|Lon',

and I have to do this for every combination of the three fields, which is a: Time consuming in itself and b: means that if a category is added, I need to then add a line of code to my view.
Is there a way of looping through the fields to dynamically create 'every Branch in the 1st record in Department for the 1st record in Division etc etc?
plus - is there a way to exclude a specific combination (given that not every combination exists in reality)?
Additional info....
'Division' is a column that contains 'Property', 'Litigation','Private Client'
'Department' is a column that contains 'High Value', 'Low Value'
'Branch' is a column that contains 'London', 'Manchester', 'Peterborough'
these are grouped columns that show summarised billing information (in the 'Net' column'
This is fine for grouping the categories downwards, what I want is a column for each combination of the three fields (eg the case statement above creates a column for 'Property|High Value|London' - I'm wondering if I can create that dynamically with a loop?  

A:

What you are asking is known as crosstab, pivot or xtab. It is backend dependant how you do it. What you are trying to do currently is the oldest style way of doing that and would be cumbersome (poor man's pivot). ie: For postgreSQL you could simply use tableFunc:
tablefunc 

