gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:12:20 27 4
gpt4 key购买 nike

我需要你的 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 行,每行中的“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'),但条件不同。你能告诉我怎么做吗?预先感谢您。

最佳答案

使用条件聚合:

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;

关于MySQL从一张表中选择具有不同条件的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50763597/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com