Pregunta

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

¿Fue útil?

Solución

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.

Otros consejos

From the docs, there's no way of altering the content of the last row.

The result set comes with a NULL value in the 1st column of the rollup row so that you can identify it in your application.

Here's a SQL Fiddle to play with it: http://sqlfiddle.com/#!8/d611d/8

As you see it does repeat the previous description in the rollup row.

use: case when itemid is null then Total

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top