mysql从一个不同条件的表中选择字段

cgvd09ve  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(356)

我需要你的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,所以max sum必须非常小。
所以,查询

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'),但条件不同。你能告诉我怎么做吗?先谢谢你。

hyrbngr7

hyrbngr71#

使用条件聚合:

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;

相关问题