如何在mysql中获得日明智的平均?

qybjjes1  于 2023-01-08  发布在  Mysql
关注(0)|答案(1)|浏览(104)

我有一个表,如下三列

Date      table_name    count
1/6/2023    table1    5161454381
1/6/2023    table2    286759521
1/6/2023    table3    43756630
1/6/2023    table4    27032087
1/6/2023    table5    44189394
1/6/2023    table6    63475022
1/5/2023    table1    5362300063
1/5/2023    table2    289459360
1/5/2023    table3    59042261
1/5/2023    table4    37256587
1/5/2023    table5    55511764
1/5/2023    table6    77917391
1/4/2023    table1    5316875841
1/4/2023    table2    282894202
1/4/2023    table3    57226525
1/4/2023    table4    36150830
1/4/2023    table5    54099874
1/4/2023    table6    75897787
1/3/2023    table1    5301932742
1/3/2023    table2    281278819

我需要为每一天以及每一张表添加一个平均值。例如,假设日期是2023-01-06,表是table 1,我需要获得过去2周同一工作日的平均值。意味着2023年1月6日的平均值(friday)是用2022-12-30和2022-12-23计算出来的,都是Friday,那么应该显示出来,那么我需要显示为透视表。

我尝试如下,但平均采取部分是不正确的,有人可以帮助改变该部分,以获得所需的输出?

SELECT
    t1.table_name as table_name,
    MAX(CASE WHEN table_date=DATE_SUB(CURDATE(), INTERVAL 4 DAY) THEN count END) AS '$date04',
    MAX(CASE WHEN table_date=DATE_SUB(CURDATE(), INTERVAL 3 DAY) THEN count END) AS '$date03',
    MAX(CASE WHEN table_date=DATE_SUB(CURDATE(), INTERVAL 2 DAY) THEN count END) AS '$date02',
    MAX(CASE WHEN table_date=DATE_SUB(CURDATE(), INTERVAL 1 DAY) THEN count END) AS '$date01',
    t2.AVG
FROM tbl t1
INNER JOIN
(
    SELECT table_name, AVG(count) AS AVG
    FROM tbl
    where table_date >= DATE(NOW() - INTERVAL 14 DAY)
    GROUP BY table_name
) t2
    ON t2.table_name = t1.table_name
where table_date >= DATE(NOW() - INTERVAL 4 DAY) and t1.table_name not in ('table7')
group by t1.table_name;
icnyk63a

icnyk63a1#

当你描述你的愿望时,我不能肯定我是否正确地理解了你的意思.
所以我猜了一下...🤔😕😉

SELECT
  table_name,
  MAX(CASE WHEN `Date` = '2023-01-03' THEN A ELSE 0 END) as Avg3,
  MAX(CASE WHEN `Date` = '2022-12-20' THEN A ELSE 0 END) as Avg3_Min2wk,
  MAX(CASE WHEN `Date` = '2023-01-04' THEN A ELSE 0 END) as Avg4,
  MAX(CASE WHEN `Date` = '2022-12-21' THEN A ELSE 0 END) as Avg4_Min2wk,
  MAX(CASE WHEN `Date` = '2023-01-05' THEN A ELSE 0 END) as Avg5,
  MAX(CASE WHEN `Date` = '2022-12-22' THEN A ELSE 0 END) as Avg5_Min2wk,
  MAX(CASE WHEN `Date` = '2023-01-06' THEN A ELSE 0 END) as Avg6,
  MAX(CASE WHEN `Date` = '2022-12-23' THEN A ELSE 0 END) as Avg6_Min2wk
FROM (
  SELECT 
    table_name,
    `Date`,
    AVG(`count`) as A
  FROM tbl
  GROUP BY table_name, `Date`
  ) x
GROUP BY table_name

输出:
| 数据表名称|平均值3|平均值3_最小值2周|平均值4|平均值4_最小值2周|平均值5|平均值5_最小值2周|平均值6|平均值6_最小2周|
| - ------|- ------|- ------|- ------|- ------|- ------|- ------|- ------|- ------|
| 表一|小行星5301932742|千|5316875841.0000美元|千|五三六二三○ ○ ○六三○ ○ ○ ○|千|小行星5161454381.0000|千|
| 表二|二八百一二七八八十九|千|小行星282894202|千|小行星289459360.0000|千|小行星286759521|千|
| 表三|千|千|57226525万美元|千|小行星5904|千|43756630.0000美元|千|
| 表四|千|千|36150830千|千|37256587千|千|小行星2703|千|
| 表五|千|千|54099874.0000美元|千|小行星55511764.0000|千|小行星44189394.0000|千|
| 表六|千|千|75897787.0000美元|千|小行星779|千|63475022千|千|

相关问题