MySQL条件分组?
我有SQL代码,返回客户id为35的总余额MySQL条件分组?,mysql,sql,group-by,Mysql,Sql,Group By,我有SQL代码,返回客户id为35的总余额 SELECT d.customer_id, SUM( IF(d.side="K" AND d.type<>"employee-cash-out", -ABS(d.total), ABS(d.total)) ) AS total, d.currency_id FROM dea_documents d WHERE d.customer_id=35 OR d.parent_customer_id=35 GROUP BY d
SELECT
d.customer_id,
SUM( IF(d.side="K" AND d.type<>"employee-cash-out", -ABS(d.total), ABS(d.total)) ) AS total,
d.currency_id
FROM dea_documents d
WHERE d.customer_id=35 OR d.parent_customer_id=35
GROUP BY d.currency_id
ORDER BY d.customer_id, d.document_date
问题是文档必须按d.customer\u id或d.parent\u customer\u id进行分组
是否可以对所有分组的客户进行选择
customer_id | total | currency_id
13 | 139749.54 | USD
13 | 4283.62 | EUR
17 | 60.00 | USD
17 | -11.57 | EUR
29 | 13498.67 | USD
29 | -347.29 | EUR
更新:
我最终得到了这个密码
SELECT
d2.customer_id,
SUM( d2.amount ) AS total,
d2.currency_id
FROM
(
SELECT
IF(parent_customer_id<>"", parent_customer_id, customer_id) AS customer_id,
currency_id,
IF(d.side="K" AND d.type<>"employee-cash-out", -ABS(d.total), ABS(d.total)) AS amount
FROM dea_documents d
) d2
GROUP BY d2.customer_id, d2.currency_id
ORDER BY total DESC
标记Barmar回答,因为它在这里帮助了我,而且是最接近的一个:在分组之前,使用联合将客户id和父客户id放入同一列:
SELECT d.customer_id,
SUM( IF(d.side="K" AND d.type<>"employee-cash-out", -ABS(d.total), ABS(d.total)) ) AS total,
d.currency_id
FROM (
SELECT customer_id, side, total, currency_id
FROM dea_documents
UNION
SELECT parent_customer_id as customer_id, side, total, currency_id
FROM dea_documents) AS d
GROUP BY d.customer_id, d.currency_id
ORDER BY d.customer_id, d.currency_id
是否应将每个文档同时添加到其自己的客户ID和其父客户ID?是否有任何原因使您无法按d.customer\u ID、d.currency\u ID进行分组?@Tim文档必须按[d.customer\u ID或d.parent\u customer\u ID]进行分组。你读过这个问题吗?@Barmar它不是必需的。如果它不是同时在两个组中,你如何确定它应该在哪个组中?这看起来是一个很好的解决方案!目前它正在返回奇怪的数量。。。我将对它进行更多的测试。如果您发布原始表数据和期望的结果,我可以尝试找出它产生奇怪结果的原因。也许你应该回答我在上面评论中提出的问题,这可能是相关的。他现在情绪低落。我将上传一些数据时,它是可访问的。
SELECT d.customer_id,
SUM( IF(d.side="K" AND d.type<>"employee-cash-out", -ABS(d.total), ABS(d.total)) ) AS total,
d.currency_id
FROM (
SELECT customer_id, side, total, currency_id
FROM dea_documents
UNION
SELECT parent_customer_id as customer_id, side, total, currency_id
FROM dea_documents) AS d
GROUP BY d.customer_id, d.currency_id
ORDER BY d.customer_id, d.currency_id