1
votes

I have a table like this:

importer     exporter     quantity    
A            D           0.9
A            B           0.9
A            B           0.1
B            E           9.4
B            E           8.9
B            D           9.4
C            P           9.0
C            V           1.0
C            P           0.9

I want to find the distinct columnA and columnB with the sum(columnC) and the table is ORDER BY SUM(columnC) DESC.

importer     exporter     quantity
B            E           18.3
C            P           9.9
B            D           9.4    
A            B           1.0
C            V           1.0
A            D           0.9

when I tried

 SELECT DISTINCT
 IMPORTER, EXPORTER, QUANTITY
 FROM Tablename;

The table MYsql shows is not distinct columnA and columnB, in fact it shows duplicated columnA and columnB and the columnC is not added up.

4
Hint: GROUP BY.Gordon Linoff
Possible duplicate of How does GROUP BY work?Sam M

4 Answers

2
votes

Try this:

SELECT   importer,
         exporter,
         SUM(quantity) AS sum_quantity
FROM     tablename
GROUP BY importer,
         exporter
ORDER BY sum_quantity DESC;
0
votes

Try like below

 SELECT 
 IMPORTER, EXPORTER, sum(QUANTITY)
 FROM Tablename group by IMPORTER, EXPORTER
0
votes

It is the basic GROUP BY:

 SELECT 
 IMPORTER, EXPORTER, SUM(QUANTITY) AS SUMQUANTITY
 FROM Tablename
 GROUP BY IMPORTER, EXPORTER
 ORDER BY SUMQUANTITY DESC;
0
votes

As hinted by @GordonLinoff, what you need is a GROUP BY query

SELECT 
    IMPORTER, 
    EXPORTER, 
    SUM(QUANTITY)
FROM Tablename
GROUP BY
    IMPORTER, 
    EXPORTER
ORDER BY 
    SUM(QUANTITY) DESC;