所以我试图改变我的sql代码(见下面的当前结果的截图+ sql)按月分组数据并总结所有的paymentSplitAmounts。每行应该是唯一的productId
所以最终的结果就像是
productID total month
1 500 11-2011
2 650 11-2011
3 250 11-2011
1 100 10-2011
2 150 10-2011
3 750 10-2011
我似乎无法正确使用语法。我哪里错了?
select
cpd.paymentId, cpd.paymentId, cpd.productId, cpd.paymentSplitAmount, cp.campaignId, cp.paymentDate
from campaign_payment_detail cpd
inner join
campaign_payment cp on cp.paymentId = cpd.paymentId
inner join product on cpd.productId = product.productId
where
1=1
and cp.campaignId = 2413
答案 0 :(得分:1)
看起来您想分组然后对结果进行排序:
SELECT cpd.productId, SUM(cpd.paymentSplitAmount), DATE_FORMAT(cp.paymentDate, '%b-%Y')
FROM campaign_payment_detail cpd
JOIN campaign_payment cp ON cp.paymentId = cpd.paymentId
JOIN product ON cpd.productId = product.productId
WHERE cp.campaignId = 2413
GROUP BY cpd.productId, DATE_FORMAT(cp.paymentDate, '%b-%Y')
ORDER BY cp.paymentDate DESC, cpd.productId ASC
编辑:使用DATE_FORMAT格式化日期。
答案 1 :(得分:1)
首先,根据您提供的查询而没有其他信息,表格产品无用..
我会这样做:
select
cpd.paymentId,
SUM(cpd.paymentSplitAmount) as total,
cp.campaignId,
cp.paymentDate
from campaign_payment_detail cpd
inner join
campaign_payment cp on cp.paymentId = cpd.paymentId
where
cp.campaignId = 2413
GROUP BY cpd.productId, cp.paymentDate
ORDER BY cpd.paymentId ASC, cp.paymentDate DESC
答案 2 :(得分:0)
您已经提到'分组'了。为此,您需要在查询中添加group by
,按照productid和month对数据进行分组,然后添加sum
以汇总paymentSplitAmount。
分组语法没有错,完全缺失。 :)
select
cpd.productId, sum(cpd.paymentSplitAmount) as total, date_format(cp.paymentDate, '%m-%Y')
from campaign_payment_detail cpd
inner join campaign_payment cp on cp.paymentId = cpd.paymentId
inner join product on cpd.productId = product.productId
where
cp.campaignId = 2413
group by cp.productId, date_format(cp.paymentDate, '%m-%Y')
order by date_format(cp.paymentDate, '%m-%Y') desc, cp.productId
这假定cp.paymentDate已包含月份。如果没有,您将必须将每个日期舍入到该月的第一天并按此分组。
现在按月分组。