Domanda

I have a mysql table that looks like the following:

  **id     name     qty**
    1      name1     1
    2      name1     1
    3      name1     1
    4      name2     1
    5      name2     1
    6      name1     1

Now when I print this on my website it writes out every single line. I would like a way to only print out lines that are unique in the name. And if there are more lines with the same name it should sum up the qty.

Currently it is printing just as above, but I would like it to print like this:

 name     qty
 name1     4
 name2     2

How would I do this without changing the mysql table?

È stato utile?

Soluzione

You have to select total quantity grouped by unique name.

Example:

select name, sum( qty ) as qty 
  from table_name
 group by name

And, if you just want to count the occurences, use count

select name, count( qty ) as qty 
  from table_name
 group by name

But, based on your data, it seems SUM is an appropriate to use.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top