Select with group by

1

I want to group the results that have the same name(varchar) and count the value(int) of the different key_id(varchar) .

Example, if the records were these:

Theresultswouldbethese(rememberingthatthekey_idvalueis"random"):

    
asked by anonymous 09.10.2017 / 09:59

2 answers

0

The only way I know of doing this exclusively with SQL would be something like this:

SELECT 
    CONCAT (
        'SELECT name, ',        
        GROUP_CONCAT(
            DISTINCT CONCAT(
                '(',
                    'SELECT IFNULL(SUM(value), 0) '
                    'FROM tabela b ',
                    'WHERE b.key_id = "', key_id, '"',
                    'AND b.name = a.name'
                ') ', key_id, ' '
            )
        ), ' '
        'FROM tabela a ',
        'GROUP BY name'
    ) INTO @sql
FROM tabela;

PREPARE stmt FROM @sql;
EXECUTE stmt;

Notice that there are 3 statements (the first generates a query, the second "prepares" the statement, and the third executes the query).

Although this works, I would only recommend using this if it is to generate a report, or for a very small database, never in an application, because for a few hundred key_ids, the DB would not swallow well. >

The best solution would be to get all the data from the table and group it according to what you need on the application side (using node / PHP / C # / Java, whatever).

    
09.10.2017 / 17:53
-1

I suggest you try the following:

select sum(value) 
from nome_da_tabela 
group by name, key_id 

The records of sum 0 will not be in the resultset, but before presenting the data in tabular format, fill in 0 (zero) cells that are empty.

    
09.10.2017 / 10:20