使用嵌套子查询的查询平均值

时间:2019-10-22 08:40:34

标签: mysql

我不知道如何计算直到每个月的每个客户的移动平均值。

我尝试使用子查询在一个大查询中编写它,并且也没有运气加入

这是我尝试使用子查询的查询:

SELECT
  date_format(z1.ServiceDate, '%y-%b') as months,
  (
    SELECT
      AVG(cc.total) + 1 AS 'avg'
    FROM
      (
        SELECT
          z.Customer_ID,
          COUNT(z.BookingId) 'total'
        from
          Orders z
        where
            YEAR(z.ServiceDate) <= YEAR(z1.months) AND
            MONTH(z.ServiceDate) <= MONTH(z1.months)
        GROUP BY
          z.Customer_ID
      ) cc
  )
from
  Orders z1
GROUP BY
  YEAR(z1.ServiceDate),
  MONTH(z1.ServiceDate)

我也试着不走运地加入这两个查询:

SELECT date_format(Orders.ServiceDate, '%y-%b') from Orders
GROUP BY YEAR(Orders.ServiceDate), month(Orders.ServiceDate)

无法与此成员一起加入:

(
SELECT AVG(cc.total) + 1 AS 'avg' FROM (
SELECT Orders.Customer_ID as 'c', 
COUNT(BookingId) 'total' from Orders
where year(Orders.ServiceDate) <= '2019' and month(Orders.ServiceDate)
<= '01'
GROUP BY Orders.Customer_ID
) cc
)

其中“ 2019”和“ 01”将从第一个查询中提取。

这是我的测试模式:

CREATE TABLE IF NOT EXISTS `orders` (
  `BookingId` INT(6) NOT NULL,
  `ServiceDate` DATETIME NOT NULL,
  `Customer_ID` varchar(1) NOT NULL,
  PRIMARY KEY (`BookingId`)
) DEFAULT CHARSET=utf8;
INSERT INTO `orders` (`BookingId`, `ServiceDate`, `Customer_ID`) VALUES
  ('1', '2019-01-03T12:00:00', '1'),
  ('2', '2019-01-04T12:00:00', '2'),
  ('3', '2019-01-12T12:00:00', '2'),
  ('4', '2019-02-03T12:00:00', '1'),
  ('5', '2019-02-04T12:00:00', '2'),
  ('6', '2019-02-012T12:00:00', '3');

我一直期待这样的事情

month    AVG
19-Jan    1.5
19-Feb    2
...
...

那里的圆点仅表明我的原始数据集中还有更多的月份。 一月份,有3个预订和2个Customer_ID。因此,截至该月的平均预订量为1.5。截至2月,已有6笔预订和3份Customer_ID。因此,新的平均值为2

1 个答案:

答案 0 :(得分:1)

加入一个子查询,该查询将不同月份返回表并进行汇总:

SELECT d.month,
  COUNT(o.bookingid) / COUNT(DISTINCT o.customer_id) avg
FROM (
  SELECT DISTINCT 
    EXTRACT(YEAR_MONTH FROM servicedate) yearmonth,
    DATE_FORMAT(servicedate, '%y-%b') month
  FROM orders
) d INNER JOIN orders o
ON EXTRACT(YEAR_MONTH FROM o.servicedate) <= d.yearmonth
GROUP BY d.yearmonth, d.month

请参见demo
结果:

| month  | avg |
| ------ | --- |
| 19-Jan | 1.5 |
| 19-Feb | 2   |