【问题标题】:count average for selected data mysql计算所选数据mysql的平均值
【发布时间】:2020-06-08 16:17:09
【问题描述】:

我有一个名为 order_star_member 的数据用户,有这个详细信息,user_id 作为用户 id,createdAt 作为交易开始,total_price_star_member 作为每个用户的交易金额。

CREATE TABLE order_star_member 
 ( users_id INT
 , createdAt DATE
 , total_price_star_member DECIMAL(10,2)
 );

INSERT INTO order_star_member  VALUES
(12,'2019-01-01',100000),
(12,'2019-01-10',100000),
(12,'2019-01-20',100000),
(12,'2019-02-10',100000),
(12,'2019-02-15',300000),
(12,'2019-02-21',500000),
(13,'2019-01-02',900000),
(13,'2019-01-11',300000),
(13,'2019-01-18',400000),
(13,'2019-02-06',100000),
(13,'2019-02-08',900000),
(13,'2019-02-14',400000),
(14,'2019-01-21',500000),
(14,'2019-01-23',200000),
(14,'2019-01-24',300000),
(14,'2019-02-08',100000),
(14,'2019-02-09',200000),
(14,'2019-02-14',100000),
(15, '2019-03-04',1000000),
(14, '2019-03-04', 300000),
(14, '2019-03-04', 350000),
(13, '2019-03-04', 400000),
(15, '2019-01-23', 620000),
(15, '2019-02-01', 650000),
(12, '2019-03-03', 750000),
(16, '2019-03-04', 650000),
(17, '2019-03-03', 670000),
(18, '2019-02-02', 450000),
(19, '2019-03-03', 750000);

我将 1 月份交易的数据用户分开,总交易量 >= 600.000

select * from order_star_member where monthname(createdAt) = 'January'
having sum(total_price_star_member) >= 600000;

结果是这样的

+----------+-------------------------+
| users_id | total_price_star_member |
+----------+-------------------------+
|       13 |               1.600.000 |
|       14 |               1.000.000 |
|       15 |                 620.000 |
+----------+-------------------------+

我想选择 1 月份总交易量 >= 600.000 的用户以及该数据用户的平均交易量。我用了这个查询

select avg(total_price_star_member) from 
(select users_Id, total_price_star_member 
from order_star_member  
where monthname(createdAt) = 'January'
group by users_id
having sum(total_price_star_member) >= 600000) a;

但为什么结果平均值是用户总数,而不是仅在每个用户一月份的总交易量> = 600.000时才计算平均值

平均值应该是 1.073.000 但为什么我使用那个查询为什么结果是 673.333

这是小提琴http://sqlfiddle.com/#!9/c77f2/11

【问题讨论】:

  • 对不起先生,让我制作小提琴谢谢您的评论
  • 再说一次,你的主键是什么?
  • users_id 先生...
  • 您的第一个查询没有 GROUP BY 子句 - 因此它无法返回发布的结果。但即使使用 GROUP BY 它也不会返回该结果。投票结束,因为不可复制。
  • 为什么会这样?请建议我我还是 mysql 的初学者

标签: mysql


【解决方案1】:

最简单的答案可能类似于以下内容(使用临时表)。由于 MySql(不在 MariaDB 中)存在临时表问题,我们需要创建其中两个:

create temporary table tmpInfo1 as
select users_id, sum(total_price_star_member) userSum
from order_star_member 
where monthname(createdAt) = 'January'
group by users_id
having sum(total_price_star_member) >= 600000;

create temporary table tmpInfo2 as select * from tmpInfo1;

select  users_id, 
        userSum, 
        (select avg(userSum) from tmpInfo2)
from tmpInfo1;


drop table tmpInfo1;
drop table tmpInfo2;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-10
    相关资源
    最近更新 更多