gpt4 book ai didi

Mysql查询多条select语句输出多列

转载 作者:行者123 更新时间:2023-11-29 03:17:20 24 4
gpt4 key购买 nike

表格

+------+-------+------------------+
|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 列的新表:

  1. 第一列应包含为每个客户记录在表中的最新值
  2. 第二列应包含过去 24 小时内每个客户的值等于 1 的时间百分比
  3. 第三列应包含过去 7 天内每个客户的值等于 1 的时间百分比
  4. 与上一栏相同,但在过去 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;

这个创建了“LAST 24 H”列

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

但我无法将所有输出放在一个新表中

最佳答案

您可以使用条件聚合。假设 8.0 之前的 MySQL,只有最近的值真的很棘手。这是一种方法:

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 扩展,其中 bool 值被视为数字上下文中的数字,1 表示真,0 表示假。

对于所讨论的时间段,平均值产生“0”或“1”,对于任何其他记录具有 NULL 值。 avg() 函数忽略 NULL 值。

关于Mysql查询多条select语句输出多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53240792/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com