Note that there are some explanatory texts on larger screens.

plurals
  1. POSQL Avoid summing rows multiple times based on LIKE expression
    primarykey
    data
    text
    <p>I have a table with bank transactions with columns id, tDate, description, cashOut, cashIn. I want to see how I spend my money, specifically at Amazon and a shop called Mazo, so I want a result like this:</p> <pre><code>Month Amazon Mazo Total 1 100 200 300 </code></pre> <p>I attempted this:</p> <pre><code>SELECT MONTH(tDate) AS Month, SUM(IF(description LIKE '%amazon%',cashOut,0)) AS Amazon, SUM(IF(description LIKE '%mazo%',cashOut,0)) AS Mazo, SUM(cashOut) AS Total FROM `transactions` GROUP BY Month </code></pre> <p>However, I got the following:</p> <pre><code>Month Amazon Mazo Total 1 100 300 300 </code></pre> <p>The problem with this SQL query is that the sum of "mazo"-transactions is wrong, because it also adds up the "amazon" transactions.</p> <p>I want the selection of the transactions to sum to be mutually exclusive or something like that, so that each transaction is part of only one of the SUMs above (without resorting to PHP or similar). (My tables contain much more data than this, and I have lots of search criteria, so it doesn't suffice to use '% mazo %' as search word. I need a general solution to the problem.)</p> <p>Does anybody have a suggestion?</p> <p><em>Details of the table and its data:</em></p> <pre><code>CREATE TABLE `transactions` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `tDate` date NOT NULL, `description` varchar(200) NOT NULL, `cashOut` decimal(10,0) NOT NULL, `cashIn` decimal(10,0) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB INSERT INTO `transactions` (`id`, `tDate`, `description`, `cashOut`, `cashIn`) VALUES (1, '2010-01-05', 'amazon', '100', '0'), (4, '2010-01-15', 'mazo', '200', '0'); </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload