MySQL 条件分组?
MySQL conditional grouping?
我有 SQL 代码 returns 客户的总余额 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.currency_id
ORDER BY d.customer_id, d.document_date
示例结果:
customer_id | total | currency_id
35 | 8.08 | USD
35 | 1.52 | EUR
问题是文档必须按(d.customer_id 或 d.parent_customer_id)分组。
是否可以对所有分组的客户进行 SELECT?:
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 的答案,因为它对我有帮助,而且是最接近的答案:)
在分组之前使用 UNION
将 customer_id
和 parent_customer_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
我有 SQL 代码 returns 客户的总余额 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.currency_id
ORDER BY d.customer_id, d.document_date
示例结果:
customer_id | total | currency_id
35 | 8.08 | USD
35 | 1.52 | EUR
问题是文档必须按(d.customer_id 或 d.parent_customer_id)分组。
是否可以对所有分组的客户进行 SELECT?:
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 的答案,因为它对我有帮助,而且是最接近的答案:)
在分组之前使用 UNION
将 customer_id
和 parent_customer_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