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

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

table

  1. +------+-------+------------------+
  2. |CLIENT| VALUE | DATETIME |
  3. +------+-------+------------------+
  4. | A | 1 | 2018-11-10 09:00 |
  5. | B | 1 | 2018-11-10 09:00 |
  6. | C | 1 | 2018-11-10 09:00 |
  7. | D | 2 | 2018-11-10 08:00 |
  8. | E | 2 | 2018-11-10 08:00 |
  9. | F | 3 | 2018-11-10 08:00 |
  10. | A | 1 | 2018-11-10 07:00 |
  11. | B | 2 | 2018-11-10 07:00 |
  12. | C | 2 | 2018-11-10 07:00 |
  13. | D | 3 | 2018-11-10 06:00 |
  14. | E | 1 | 2018-11-10 06:00 |
  15. | F | 2 | 2018-11-10 06:00 |
  16. | A | 1 | 2018-11-08 08:00 |
  17. | B | 2 | 2018-11-08 08:00 |
  18. | C | 2 | 2018-11-08 08:00 |
  19. | D | 1 | 2018-11-08 08:00 |
  20. | E | 1 | 2018-11-08 07:00 |
  21. | F | 2 | 2018-11-08 07:00 |

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

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

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

  1. SELECT
  2. client,
  3. value,
  4. max(datetime)
  5. FROM
  6. table
  7. GROUP BY
  8. client;

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

  1. SELECT
  2. client,
  3. count(if(value = 1,1, null))/count(value),
  4. FROM
  5. table
  6. WHERE
  7. date(datetime) < CURRENT_DATE() - interval 1 day
  8. GROUP BY
  9. repository_name;

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

wn9m85ua

wn9m85ua1#

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

  1. select t.client,
  2. max(case when t.datetime = c.maxdt then t.value end) as most_recent_value,
  3. avg(case when t.datetime >= now() - interval 1 day
  4. then (t.value = 1)
  5. end) as last_day_percentage,
  6. avg(case when t.datetime >= now() - interval 7 day
  7. then (t.value = 1)
  8. end) as last_7day_percentage,
  9. avg(case when t.datetime >= now() - interval 30 day
  10. then (value = 1)
  11. end) as last_30day_percentage
  12. from t join
  13. (select t.client, max(t.datetime) as maxdt
  14. from t
  15. group by t.client
  16. ) c
  17. on c.client = t.client
  18. group by t.client;

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

展开查看全部

相关问题