Note that there are some explanatory texts on larger screens.

plurals
  1. POMySQL Query with several "for each"
    primarykey
    data
    text
    <p>I have this table:</p> <pre><code>idTransactions idCampaignsList idMemberCard amountOriginal amountFinal dateTransaction 1 2 1 50.00 100.00 2012-10-31 12:45:41 2 3 1 0.00 -50.00 2012-10-31 12:47:25 3 2 2 255.00 255.00 2012-10-31 17:19:07 4 1 2 95.00 95.00 2012-11-02 20:38:36 5 3 2 0.00 -400.00 2012-11-02 20:39:50 24 1 4 10.00 2.00 2012-11-03 11:16:3 </code></pre> <p>With this query</p> <pre><code>SELECT SUM(amountOriginal) AS euro, SUM(amountFinal) AS deducted, EXTRACT(YEAR_MONTH FROM(dateTransaction)) AS period FROM transactions INNER JOIN campaignsList ON campaignsList.idCampaignsList = transactions.idCampaignsList INNER JOIN customers ON customers.idCustomer = campaignsList.idCustomer WHERE customers.idCustomer = 14 AND transactions.idCampaignsList = 2 GROUP BY period ORDER BY period </code></pre> <p>I obtain this result</p> <pre><code>euro deducted period 305.00 305.00 201210 14860.46 -22758.50 201211 1845.00 -34710.00 201212 </code></pre> <p>For last 12 month, sum of "charged" and discharged.</p> <p>Now, idCampaignsList could be 1, 2, also 500, it depend on how many "campaigns" have my idCustomer (retrieved via JOIN).</p> <p>I'd like have a query dinamic, that, "for each" idCampaignsList, print me sum of amountOriginal and amountFinal.</p> <p>To intend, from previos table, i would like to have</p> <pre><code>idCampaignsList SUM(amountOriginal) SUM(amountFinal) period 1 50 50 201210 2 255 255 201210 2 95 -305 201211 4 10 2 201211 </code></pre> <p>So, for every period, sum columns for every distinct idCampaignsList, where idCampaignsList is dinamically (SELECT idCampaignsList FROM myOtherTable where idCustomer = 14)</p>
    singulars
    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.
 

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