I tried to find this question somewhere else on here, and found a couple that were similar to it — but all the answers seemed pretty convoluted, and I think it was surprising to me because I just imagined that SQL would have a way easier way to do this.
Essentially, I'm using a GROUP BY
to group two values on top of each other. The coding is simple and works well, where I get these results using WITH ROLLUP
at the end:
Type Person Count
Type A Person 1 10
Type A Person 2 91
Type A Person 3 13
Type A Person 4 10
Type A Person 5 2
Type A NULL 126
Type B Person 6 16
Type B Person 7 63
Type B Person 8 15
Type B Person 9 22
Type B Person 10 16
Type B Person 11 3
Type B Person 12 20
Type B Person 13 44
Type B NULL 198
NULL NULL 360
Is there an easy way to substitute something saying if "NULL" is in the "Person" column, then make NULL AS "Subtotal"
and if "NULL" is in the "Type" column, NULL AS "Grand Total?"
And if that's weirdly complicated, I'd be totally fine with just calling all of them "Total."
Thanks!
Best Answer
Let's say your query looks like this:
The
NULL
values coming out can be substituted with something like this...Using IFNULL() will forcibly put those Text String in place of the
NULL
for each level of theGROUP BY
. As an example, here are past posts where I actively substituteNULL
in my answer involvingWITH ROLLUP
:Sep 13, 2011
: Determining max database and table size supported and present sizeDec 01, 2011
: MySQL Workbench Database SizesJan 11, 2013
: Translating backup size to database sizeFrom these posts I have this example,
Here is the output from one of my client's DB Servers:
Notice I check the ISNULL() of each column and compare IF() function calls to produce a single column output. In your particular case, you are going to need one of these two queries
QUERY #1
QUERY #2
Here is some sample data:
Here is that sample data loaded:
Now, here is the output of Query #1:
Now, here is the output of Query #2:
Give it a Try !!!