Home > Mobile >  Sum different values of same type in same column in one SQL query
Sum different values of same type in same column in one SQL query

Time:06-13

At the moment im doing the following to count the payment methods in different languages in a column:

$sql = "SELECT `payment`, count(*) as number FROM Test GROUP BY `payment` ";

Result:

Cash 2
Bar 4
Credit-Card 5
Kreditkarte 8
Invoice 12
Rechnung 27

Any idea how to sum the same payment methods in different languages in one SQL query to get the following without the part in the brackets obviously:

Bar 6 (sum of Cash and Bar)
Kreditkarte 13 (sum of Credit-Card and Kreditkarte)
Rechnung 39 (sum of Invoice and Rechnung)

Table Name: Test

payment       
===========
Cash
Bar
Credit-Card
Kreditkarte
Invoice
Rechnung

CodePudding user response:

Use a CASE expression that changes 'Cash' to 'Bar', 'Credit-Card' to 'Kreditkarte' and 'Invoice' to 'Rechnung' and group by its result:

SELECT CASE payment
         WHEN 'Cash' THEN 'Bar'
         WHEN 'Credit-Card' THEN 'Kreditkarte'
         WHEN 'Invoice' THEN 'Rechnung'
         ELSE payment
       END AS payment, 
       COUNT(*) AS number 
FROM Test 
GROUP BY 1;
  • Related