0

I am trying to calculate in an easy way that will allow me to manage the following database table:

code ----- companyID ----- bought----- returned
abcd ----- 32        ----- 1       ----- 0
efgh ----- 32        ----- 1       ----- 1
ijkl ----- 58        ----- 1       ----- 1
mnop ----- 65        ----- 1       ----- 0

and I am trying to get the desired (below result) with this query

SELECT COUNT(*) AS bought, companyID FROM table 
WHERE bought= 1 AND refunded = 0

UNION ALL 
SELECT COUNT(*) AS returned, companyID FROM table 
WHERE returned= 1

GROUP BY companyID

which is wrong.

Here is the desired output:

companyID ----- codesTotal ----- boughtTotal ----- returnedTotal
32        ----- 2          ----- 2            ----- 1
58        ----- 1          ----- 1            ----- 1 
65        ----- 1          ----- 1            ----- 0 

The numbers of rows of a companyID must be equal to the boughtTotal.

How can I edit the code in order to achieve this?

EnexoOnoma
  • 8,454
  • 18
  • 94
  • 179
  • The specified "duplicate" referenced string columns. This problem has flags which is a different (and simpler) solution. – Gordon Linoff Apr 20 '20 at 01:27

1 Answers1

0

Is this what you want?

select companyid,
       count(*) as num_codes,
       sum(bought) as num_bought,
       sum(returned) as num_returned
from t
group by companyid;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786