mysql查询多列上输出的多个select语句

06odsfpq  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(319)

table

+------+-------+------------------+
|CLIENT| VALUE |    DATETIME      |
+------+-------+------------------+
|  A   |  1    | 2018-11-10 09:00 |
|  B   |  1    | 2018-11-10 09:00 |
|  C   |  1    | 2018-11-10 09:00 |
|  D   |  2    | 2018-11-10 08:00 |
|  E   |  2    | 2018-11-10 08:00 |
|  F   |  3    | 2018-11-10 08:00 |
|  A   |  1    | 2018-11-10 07:00 |
|  B   |  2    | 2018-11-10 07:00 |
|  C   |  2    | 2018-11-10 07:00 |
|  D   |  3    | 2018-11-10 06:00 |
|  E   |  1    | 2018-11-10 06:00 |
|  F   |  2    | 2018-11-10 06:00 |
|  A   |  1    | 2018-11-08 08:00 |
|  B   |  2    | 2018-11-08 08:00 |
|  C   |  2    | 2018-11-08 08:00 |
|  D   |  1    | 2018-11-08 08:00 |
|  E   |  1    | 2018-11-08 07:00 |
|  F   |  2    | 2018-11-08 07:00 |

我是mysql的新手,这个查询给我带来了麻烦。
我只有一个名为“table”的表,它有三列。
此表每天在不同的时间从一组特定的客户机a、b、c、d、e、f记录许多数据
对于一个查询,我需要为每个客户机创建一个新表,其中包含一行和以下4列:
第一列应该包含表中为每个客户机记录的最新值
第二列应包含每个客户端在过去24小时内值等于1的时间百分比
第三列应包含每个客户在过去7天内值等于1的时间百分比
与上一栏相同,但在过去30天内
我希望有人能帮助我。
我想要的是:

+------+-------------+-----------+--------------+--------------+
|CLIENT| NEWEST VALUE| LAST 24 H | LAST 7 DAYS  | LAST 30 DAYS |
+------+-------------+-----------+--------------+--------------+
|  A   |       1     |    100%   |      100%    |     ...      | 
|  B   |       1     |     50%   |       66%    |     ...      |
|  C   |       1     |     50%   |       33%    |     ...      |
|  D   |       2     |      0%   |       33%    |     ...      |
|  E   |       2     |     50%   |       66%    |     ...      |
|  F   |       3     |      0%   |        0%    |     ...      |

这段代码可以很好地创建“newst value”列

SELECT
    client,
    value,
    max(datetime)
FROM
    table
GROUP BY
    client;

这个是“最后24小时”专栏

SELECT
    client,
    count(if(value = 1,1, null))/count(value),
FROM
    table
WHERE
    date(datetime) < CURRENT_DATE() - interval 1 day
GROUP BY
    repository_name;

但是我不能把所有的输出放在一个新表中

dpiehjr4

dpiehjr41#

可以使用条件聚合。假设mysql是8.0之前的版本,只有最新的值才是真正棘手的。这里有一种方法:

select t.client,
       max(case when t.datetime = c.maxdt then t.value end) as most_recent_value,
       avg(case when t.datetime >= now() - interval 1 day
                then (t.value = 1)
           end) as last_day_percentage,
       avg(case when t.datetime >= now() - interval 7 day
                then (t.value = 1)
           end) as last_7day_percentage,
       avg(case when t.datetime >= now() - interval 30 day
                then (value = 1)
           end) as last_30day_percentage                
from t join
     (select t.client, max(t.datetime) as maxdt
      from t
      group by t.client
     ) c
     on c.client = t.client
group by t.client;

请注意,此逻辑使用mysql扩展,其中布尔值在数字上下文中被视为数字,1表示true,0表示false。
平均值为所讨论的时间段生成“0”或“1”,其中 NULL 任何其他记录的值。这个 avg() 函数忽略 NULL 价值观。

相关问题