0

My table is, I know that the table terrible but is old: http://sqlfiddle.com/#!9/f2680/1

+----+-----------------------+----------+------+
| ID | COUNTRY               | QUANTITY | EACH |
+----+-----------------------+----------+------+
| 1  | U.S.A                 |     1    |  12  |
| 2  | U.K.                  |     2    |   3  |
| 3  | GERMANY               |   NULL   |   3  |
| 4  | FRANCE;GERMANY; U.S.A |     0    |   7  |
| 5  | U.S.A;GERMANY         |     3    |   8  |
| 6  | GERMANY;FRANCE;U.S.A  |     1    |  10  |
+----+-----------------------+----------+------+

<?php
include 'bd_cnx.php';
  $ret =[['Test','Valori livrare']];
  $sql = "SELECT SUBSTRING_INDEX(COUNTRY, ';', 1) AS COUNTRY,
                 SUM(COALESCE(IF(QUANTITY = NULL OR QUANTITY = 0,1,QUANTITY),1) * EACHCOL) AS PRICE
          FROM table1
          GROUP BY COUNTRY";

  $result = $conn->query($sql);
  if ($result->num_rows > 0){
    while($row = $result->fetch_assoc()){
      $ret[] =[$row['COUNTRY'], floatval($row['PRICE'])];
    }
 }
  echo json_encode($ret);
?>
My SQL code returns rows: FRANCE=3, GERMANY=6, GERMANY=12, U.S.A=12, U.S.A=7

I want to group the resulted values from the COUNTRY column (to make them unique) and then make SUM and finaly to result the next form: FRANCE=3; GERMANY=18; U.S.A=19. I will introduce these rows in google chart in the next form: ['country','value']. Thank you!

2
  • So, what's the question? Commented Aug 29, 2016 at 19:54
  • 1
    stackoverflow.com/a/32620163 Commented Aug 29, 2016 at 19:58

1 Answer 1

1

Use this query with additional select ... group by on the first query:

select COUNTRY, sum(PRICE) from(
SELECT
  SUBSTRING_INDEX(COUNTRY, ';', 1) AS COUNTRY,
  SUM(COALESCE(IF(QUANTITY = NULL OR QUANTITY = 0,1,QUANTITY),1) * EACHCOL) AS PRICE
FROM table1
GROUP BY COUNTRY) as t
group by COUNTRY;
Sign up to request clarification or add additional context in comments.

1 Comment

@ Andrej Ludinovsckov For those who will have my problem, and public response to this post stackoverflow.com/questions/39212444/… Thank you !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.