我有这张桌子:
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
使用此查询
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
我获得了这个结果
euro deducted period
305.00 305.00 201210
14860.46 -22758.50 201211
1845.00 -34710.00 201212
过去12个月,“收费”和已解除的总和。
现在,idCampaignsList可以是1,2,也就是500,它取决于我的idCustomer(通过JOIN检索)有多少“广告系列”。
我想要查询dinamic,“对于每个”idCampaignsList,打印amountOriginal和amountFinal的总和。
打算,从previos表,我想
idCampaignsList SUM(amountOriginal) SUM(amountFinal) period
1 50 50 201210
2 255 255 201210
2 95 -305 201211
4 10 2 201211
因此,对于每个句点,为每个不同的idCampaignsList汇总列,其中idCampaignsList是dinamically(SELECT idCampaignsList FROM myOtherTable,其中idCustomer = 14)
答案 0 :(得分:1)
我想要查询dinamic,即“为每个”idCampaignsList打印 我总和金额原始金额和金额最终。
我认为你所说的several For each
是GROUP BY transactions.idCampaignsList
。
尝试将transactions.idCampaignsList
添加到SELECT
列表,从transactions.idCampaignsList = 2
子句中删除谓词WHERE
,并将GROUP BY
子句中的该列列为好吧,就像这样:
SELECT
transactions.idCampaignsList
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
GROUP BY period, transactions.idCampaignsList
ORDER BY period