MySQL从一个具有不同条件的表中选择字段

时间:2018-06-08 15:10:22

标签: mysql sql select join

我需要你的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()函数的结果很奇怪,因为我只有300行和'值'每行中的字段等于 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'),但条件不同。 你能告诉我怎么样吗?提前谢谢。

1 个答案:

答案 0 :(得分:1)

使用条件聚合:

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;