Mysql histogram with negative values

I have a table like this:

ID | value
----------
1  |  -3 
2  |  -4
3  |   5
4  |   2

      

and I want to show a histogram in mysql like this:

ID | value | histogram
-------------------------
1  |  -3   | ***
2  |  -4   |****
3  |   5   |    *****
4  |   2   |    **

      

I cannot figure out how to represent negative values.

+3


source to share


1 answer


This can be done with Monkey Business Operations. But you will need to display the resulting text strings in a monospaced font. In many fonts, whitespace takes up less space than star characters, so the zero points don't line up if you display those star strings this way.

First, the expression IF(value<0, -value, 0)

will produce 5

if value

equal -5

and zero otherwise.

Second, the expression REPEAT('*', IF(value<0,-value,0))

will give you five consecutive stars from this value -5

and there will be no stars with any positive value.

Third, it REVERSE(RPAD(REPEAT('*', IF(value<0,-value,0)), 20, ' '))

will provide you with a text string 20 characters long, ending with five stars in a row. This is how you make the negative part of your little diagram.



Finally, connect to REPEAT('*',IF(value<0,0,value))

get something useful for positive instances value

.

This should do it for you.

SELECT id,
       value,
       CONCAT( REVERSE(RPAD(REPEAT('*', IF(value<0,-value,0)), 20, '=')),
               REPEAT('*',IF(value<0,0,value))
              ) AS histogram
  FROM t
 ORDER BY id

      

Note that I have hard coded 20

as the largest negative value that will work here. You could do something more complex if you need to.

+1


source







All Articles