I am running a query for a report and am using rollup to get a total. One of my columns have a text field that is duplicating at the end. For example:
SELECT * FROM transactions;
transNum | itemid | description | qty
---------------------------------------
01 | 01 | DESC1 | 14
02 | 01 | DESC1 | 05
03 | 01 | DESC1 | 01
04 | 02 | DESC2 | 02
05 | 02 | DESC2 | 01
06 | 02 | DESC2 | 02
07 | 03 | DESC3 | 05
08 | 03 | DESC3 | 06
09 | 03 | DESC3 | 01
SELECT itemid,description,qty FROM transactions GROUP BY id WITH ROLLUP;
itemid | description | qty
----------------------------
01 | DESC1 | 20
02 | DESC2 | 05
03 | DESC3 | 12
| DESC3 | 37
This is a rough example, my actual data consists of multiple tables.
Now, I understand that the DESC3 is getting duplicated because I am not grouping by the description field, but is there any function that can get around this?
Other database engines have a GROUPING function, which is basically what I need but in MySQL.
Thank you for any help
OK, then try this:
SELECT a.itemid, b.description, a.total
FROM
(
SELECT itemid, sum(qty) as total
FROM transactions
GROUP BY itemid WITH ROLLUP
) as a
LEFT JOIN item b ON a.itemid=b.itemid
Assuming you have a table named item
with item descriptions keyed on itemid
.