I have a database that contains phone call records (I am NOT a telemarketer, this is emergency call data). Each row is a call record. Some of the columns contain timing information. There is also a priority column for each call. It looks like this:
PRIORITY TIMING1 TIMING2 TIMING3
-----0----------22----------3-----------43
-----1----------42----------10----------12
-----0----------12----------13----------6
-----2----------23----------12----------37
-----1----------12----------16----------23
The output that I need is basically this one row per timing with the sum of all the time grouped by priority as columns. There are a fixed number of timings and priorities that I know of ahead of time. It would look like this:
------------Priority 0-------Priority 1-------Priority 2
Timing1----123--------------332--------------233
Timing2----265--------------241--------------302
Timing3----387--------------192--------------201
Is it possible to do something like this in a single query? The query also has to be runnable on a mobile platform that is fairly resource constrained, although time to run isn’t a huge deal. Given the size of this table and the memory issue I would rather avoid temporary tables.
You can use
UNPIVOTandPIVOTfor this:Here is a Static Version of the query – a static version means that you hard-code the values.
see SQL Fiddle with Demo
You can also do this Dynamically:
see SQL Fiddle with Demo
Edit #1, you stated in the comments that you are using SQLite which does not have a
PIVOTfunction. But you can still do this using aUNION ALLand then an aggregate function with aCASE:see SQL Fiddle with Demo