0

我有一张这样的桌子,

CREATE TABLE order_match
    (`order_buyer_id` int, `createdby` int, `createdAt` datetime, `quantity` decimal(10,2))
;

INSERT INTO order_match
    (`order_buyer_id`, `createdby`, `createdAt`, `quantity`)
VALUES
    (19123, 19, '2017-02-02', 5),
    (193241, 19, '2017-02-03', 5),
    (123123, 20, '2017-02-03', 1),
    (32242, 20, '2017-02-04', 4),
    (32434, 20, '2017-02-04', 5),
    (2132131, 12, '2017-02-02', 6)
;

这是这个表的小提琴 ,order_buyer_id是交易的id,createdby是买家,createdAt是每次交易的时间,数量是交易的数量

我想找出每个重复订单的最大值、最小值、中值和平均值(交易> 1的买家)

所以在这张桌子上,预期的结果就是这样

+-----+-----+---------+--------+
| MAX | MIN | Average | Median |
+-----+-----+---------+--------+
|   3 |   2 |     2.5 |      3 |
+-----+-----+---------+--------+

注意:我使用的是 mysql 5.7

我正在使用这种语法

select -- om.createdby, om.quantity, x1.count_
       MAX(count(om.createdby)) AS max,
       MIN(count(om.createdby)) AS min,
       AVG(count(om.createdby)) AS average
  from (select count(xx.count_) as count_
          from (select count(createdby) as count_ from order_match
                 group by createdby
                 having count(createdby) > 1) xx
        ) x1,
        (select createdby
           from order_match
          group by createdby
          having count(createdby) > 1) yy,
        order_match om
 where yy.createdby = om.createdby
   and om.createdAt <= '2017-02-04'
   and EXISTS (select 1 from order_match om2
                where om.createdby = om2.createdby
                  and om2.createdAt >= '2017-02-02'
                  and om2.createdAt <= '2017-02-04')

但据说

Invalid use of group function
4

1 回答 1

1

我们可以尝试通过 聚合createdby,然后获取您想要的聚合:

SELECT
    MAX(cnt) AS MAX,
    MIN(cnt) AS MIN,
    AVG(cnt) AS Average
FROM
(
    SELECT createdby, COUNT(*) AS cnt
    FROM order_match
    GROUP BY createdby
    HAVING COUNT(*) > 0
) t

在 MySQL 5.7 中模拟中位数需要大量工作,而且很丑陋。如果您长期需要中位数,请考虑升级到 MySQL 8+。

于 2020-03-19T04:38:21.343 回答