0

I have a column named purchasetype which contains three kind of values new,trial,new,trial another column in noofsales
I am counting the total number based on the purchasetype
The query I am using is

   Select SUM(noofsales) 
     From table 
  GroupBy purchasetype

This query is giving me 3 kind of sum result new,trial and new,trial
I want total sum in new and trial only if one record contains new,trial then one count should increase for new and also one count should increase for trial
I have tried using substring_index function like

Select SUM(noofsales) 
     From table 
  Groupby substring_index(PurchaseType, ',', 0)

but this is summing up only for the first record in comma separated value.

Dharman
  • 30,962
  • 25
  • 85
  • 135

2 Answers2

0

In your case you can use CASE/WHEN statement for each sum. For example:

SELECT query with CASE condition and SUM()

stepozer
  • 1,143
  • 1
  • 10
  • 22
0

You could create a number table on the fly, and use it to turn records where purchase_type is a comma separated value into new rows. Then in the outer query you can aggregate properly.

Consider the following query, that you can see in action in this db fiddle. It will dynamically discover the available purchase types and generate the result that you expect :

SELECT x.purchase_type, SUM(x.noofsale)
FROM (
    SELECT
        t.noofsale,
        SUBSTRING_INDEX(SUBSTRING_INDEX(t.purchase_type, ',', numbers.n), ',', -1) purchase_type
    FROM
        (SELECT 1 n UNION SELECT 2) numbers 
        INNER JOIN t ON CHAR_LENGTH(t.purchase_type) - CHAR_LENGTH(REPLACE(t.purchase_type, ',', ''))>= numbers.n-1
) x
GROUP BY x.purchase_type
ORDER BY 1,2

NB : this query supports maximum two comma-separated values (as shown in your sample data) ; if you expected more than that, you may adapt the numbers subquery :

(SELECT 1 n UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 ...)
GMB
  • 216,147
  • 25
  • 84
  • 135