首页 > 解决方案 > MySQL 从具有不同条件的一张表中选择字段

问题描述

我需要你的 mysql 查询帮助。我有一张表“指标”:

create table metrics
(
  guid          binary(16)  not null
    primary key,
  entry_guid    binary(16)  not null,
  customer_guid binary(16)  null,
  metrics       varchar(30) not null,
  value         int         not null,
  `_created`    timestamp   null,
  `_updated`    timestamp   null
);

所以,我正在尝试做这样的事情:

SELECT t1.entry_guid as entry_guid, SUM(t1.`value`) as last_week, SUM(t2.`value`) as last_month
FROM metrics as t1, metrics as t2
  WHERE t1.`_created` > NOW() - INTERVAL 7 DAY OR t2.`_created` > NOW() - INTERVAL 1 MONTH
GROUP BY t1.entry_guid

但结果我得到了使用 SUM() 函数的相同奇怪结果

entry_guid                          last_week  last_month
1                                   4613       4613
2                                   207        207
3                                   6003       6003
4                                   9108       9108

此外 SUM() func 的结果很奇怪,因为我只有 300 行,每行中的 'value' 字段等于1,所以最大总和必须很小。

所以,查询

SELECT t1.entry_guid as entry_guid, SUM(t1.`value`) as sum
FROM metrics as t1
GROUP BY t1.entry_guid

给我

entry_guid                          sum
0x34303535636637643538396665633265  21
0x34313830656231666665393131326635  21
0x34336537663033653963303437356165  1
0x34363061653730313738313263386264  44

我需要从一张表中获取 SUM('value'),但条件不同。你能告诉我怎么做吗?先感谢您。

标签: mysqlsqlselectjoin

解决方案


使用条件聚合:

SELECT m.entry_guid as entry_guid,
       SUM(CASE WHEN m.`_created` > NOW() - INTERVAL 7 DAY THEN t1.`value` ELSE 0 END) as last_week,
       SUM(CASE WHEN m.`_created` > NOW() - INTERVAL 1 MONTH THEN t2.`value` ELSE 0 END) as last_month
FROM metrics m
GROUP BY m.entry_guid;

推荐阅读