Here’s a rough idea of what I have:
+---------------+ +-----------------+ +---------------+
| customers | | transactions | | branches |
+---------------+ +-----------------+ +---------------+
| customerid | | orderid | | branchid |
| | | customerid (FK) | | |
| | | branchid (FK) | | |
+---------------+ | datetime | +---------------+
+-----------------+
How would I create a query which pulls in the count of transactions per day/week/etc. but for each branchid separately?
I have tried an union such as this (count for all Saturdays only). Which gives a result but not in the format desired.
SELECT COUNT(orderid) as count1 FROM transactions WHERE WEEKDAY(datetime) = 5
AND branchid = 'branch1'
UNION
SELECT COUNT(orderid) as count2 FROM transactions WHERE WEEKDAY(datetime) = 5
AND branchid = 'branch2'
returns:
+------------+
| count1 |
+------------+
| 152 |
| 48 |
+------------+
Whereas I would like the data to be formatted as follows:
+------------+------------+
| count1 | count2 |
+------------+------------+
| 152 | 48 |
| | |
+------------+------------+
Does anyone have any hints on how this can be done? Thanks in advance!
There are a few ways to accomplish this. Using the
UNIONyou already have, you can build a pivot query around a subquery. This version adds a staticnameto each of the columns in your original UNION and uses them to differentiate aCASEstatement on the outer query.In your case, it could be done with subselects inside the
SELECTlist, however this method is more extensible to other kinds of pivot queries and is the more general convention for achieving them.