0

假设我有 2 个表:成员和订单(Mysql)

Members : 
id   |   name
1    |   Lee
2    |   brad
Orders : 
id   |   member_id   |   status (1: paid, 2: unpaid)   |    total
1    |   1           |   1                             |   1000000 
2    |   1           |   1                             |   1500000
3    |   1           |   2                             |   1300000
4    |   2           |   1                             |   3000000 
5    |   2           |   2                             |   3500000
6    |   2           |   2                             |   3300000

我有一个 sql 查询:

SELECT m.name,
       o.member_id,
       COUNT(o.id)  AS number_of_order,
       SUM(o.total) AS total2
FROM   orders o
       LEFT JOIN members m
              ON o.member_id = m.id
GROUP  BY o.member_id

这给了我这个:

name   |   number_of_order   |   total2
Lee    |   3                 |   3800000
brad   |   3                 |   9800000

我想要的只是这样的:

    name   |   number_of_order   |   total2
           |  Paid        Unpaid | Paid      Unpaid
    ------------------------------------------------
    Lee    |         3           |   3800000
           |  2             1    | 2500000   1300000
    ------------------------------------------------
    brad   |         3           |   9800000
           |  1             2    | 3000000   6800000
    ------------------------------------------------

如何进行可以给我结果的查询?

谢谢你的时间!

4

2 回答 2

4

您可以在SUM/COUNT函数中使用条件。

SELECT 
  m.name,
  COUNT(o.id) AS number_of_order,
  SUM(o.total) AS total2,
  COUNT(IF(o.status=1, 1, NULL)) AS paid_order,
  COUNT(IF(o.status=2, 1, NULL)) AS unpaid_order,
  SUM(IF(o.status=1, o.total, 0)) AS paid,
  SUM(IF(o.status=2, o.total, 0)) AS unpaid
FROM orders o 
LEFT JOIN members m ON o.member_id=m.id
GROUP BY o.member_id
于 2012-08-30T03:36:39.017 回答
0

尝试使用不同的别名和 where 子句多次列出订单表。就像是:

SELECT m.name,
       COUNT(po.id),
       COUNT(uo.id),
       COUNT(o.id),
       SUM(po.total),
       SUM(uo.total),
       SUM(o.total)
FROM   members m,
       orders o,
       orders po,
       orders uo
WHERE  o.member_id = m.id
       AND po.member_id = m.id
       AND uo.member_id = m.id
       AND po.status = 1
       AND uo.status = 2
GROUP  BY m.name

这并不完全符合您的要求,但它应该让您朝着正确的方向前进。

于 2012-08-30T03:42:57.030 回答