SQL 获取 col 值之和大于 X 的行

问题描述 投票:0回答:1

我有一张这样的桌子

|编号 |日期 |容量|仓库|保留 |订单_id
| 1 | 2024-04-29 | 69 | 69 1 | 0 | 0 |
| 2 | 2024-04-29 | 49 | 49 1 | 0 | 0 |
| 3 | 2024-04-29 | 69 | 69 1 | 0 | 0 |
| 4 | 2024-04-29 | 69 | 69 1 | 0 | 0 |

现在我只想得到“容量”总和接近 100 的行 - 所以我的输出应该是

|编号 |日期 |容量|仓库|保留 |订单_id
| 1 | 2024-04-29 | 69 | 69 1 | 0 | 0 |
| 2 | 2024-04-29 | 49 | 49 1 | 0 | 0 |

你能帮我找到正确的SQL语句吗?

我已经尝试对容量求和并按 id 对其进行分组,总和 >= 100 但我仍然没有得到结果

sql mysql
1个回答
0
投票

请参阅链接的小提琴,但我能够获得您提供的测试数据的结果:

create table test (
id int,
  date date, 
  capacity int, depot int,
  reserved tinyint(1),
  order_id int);
  
insert into test values (1, '2024-04-29', 69, 1, 0, 0), (2, '2024-04-29', 49, 1 ,0 ,0),
( 3, '2024-04-29', 69,1, 0, 0),
(4 ,'2024-04-29' ,69 , 1, 0 , 0);
Records: 4  Duplicates: 0  Warnings: 0

这里我假设您想按日期求和,但如果不是这种情况,您应该能够轻松交换聚合列:

select date, sum(capacity) as total from test group by date having total > 100;
日期 总计
2024-04-29 256

小提琴

© www.soinside.com 2019 - 2024. All rights reserved.