Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - show field value only in first instance of each grouped value?

I don't think this is possible, but I would like to be proved otherwise.

I have written a simple report viewing class to output the results of various database queries. For the purpose of improving the display, when I have a report with grouped data, I would like to display the field value only on the first row of each unique value - and I would like to do this at the query level, or it would necessitate additional logic in my class to determine these special values.

It will probably help to illustrate my requirements with a simple example. Imagine this dataset:

Year    Quarter    Total
2008    Q1         20
2008    Q2         25
2008    Q3         35
2008    Q4         40
2009    Q1         15
2009    Q2         20
2009    Q3         30
2009    Q4         35

If possible, I would like the dataset returned as:

Year    Quarter    Total
2008    Q1         20
        Q2         25
        Q3         35
        Q4         40
2009    Q1         15
        Q2         20
        Q3         30
        Q4         35

Is there any way of doing this progammatically in MySQL?

like image 536
BrynJ Avatar asked Jan 30 '26 00:01

BrynJ


1 Answers

SELECT  CASE WHEN @r = year THEN NULL ELSE year END AS year,
        quarter,
        total,
        @r := year
FROM    (
        SELECT  @r := 0
        ) vars,
        mytable
ORDER BY
        year

@r here is a session variable. You can use these in MySQL like any variable in any procedural language.

First, it's initialized to zero inside the subquery.

Second, it's checked in the SELECT clause. If the current value of @r is not equal to year, then the year is output, else NULL is output.

Third, it's updated with current value of year.

like image 112
Quassnoi Avatar answered Jan 31 '26 15:01

Quassnoi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!