简体   繁体   中英

MySQL select field from one table with different conditions

I need your help with mysql query. I have one table 'metrics':

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
);

So, I'm trying to do something like this:

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

But in result i get identical strange result of using SUM() function

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

Moreover result of SUM() func is strange, because I have only 300 rows and 'value' field in each row is equal 1 , so max sum must be very little.

So, the query

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

gives me

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

I need to get SUM('value') from one table, but with different conditions. Can you show me how? Thank you in advance.

Use conditional aggregation:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM