gpt4 book ai didi

mysql - 使用 having 添加一个新的选择字段

转载 作者:行者123 更新时间:2023-11-29 05:02:51 25 4
gpt4 key购买 nike

是mysql的问题。
这是一个简单的表,需要按groupid分组。(只是编造的,除了解决问题外没有其他用途)

id car  house  pets   groupid1   1     2    1        11   0     1    0        11   0     0    0        1
SELECT SUM(car),SUM(house),SUM(pets) FROM table GROUP BY id

所以结果是

car 1 house 3 pets 1

我想做的是向组“any_record_with_all_zeros”插入一个新的选定字段,如果该组有一行 car=0 house=0 pets=0,则该字段为 0

所以想要的结果是

car 1,house 3, pets 1, any_record_with_all_zeros = 1 

如果 id 3 行的任何字段不是 0,则“any_record_with_all_zeros 为 0”

我知道我应该使用 HAVING,但我不知道如何将“any_record...”字段放入 SELECT 部分。

SELECT  SUM(car),SUM(house),SUM(pets),any_record_with_all_zerosFROM  tableGROUP BY groupidHAVING if car=0 && house=0 && pets=0 than any_record_with_all_zeros = 0 or something similar

有什么想法吗?

最佳答案

对两个 Bitwise OR 的 NOT 求和也有效。

create table `table` (
id int primary key auto_increment,
groupid int not null,
car int not null default 0,
house int not null default 0,
pet int not null default 0
);
insert into `table` (groupid, car, house, pet) values
(1, 1, 2, 1)
,(1, 0, 1, 0)
,(1, 0, 0, 0)
-- ,(1, 0, 0, 0)
-- ,(1, 0, 0, 0)
;
SELECT 
groupid,
SUM(car) as cars,
SUM(house) as houses,
SUM(pet) as pets,
SUM(not(car | house | pet)) as none
FROM `table`
GROUP BY groupid
groupid | cars | houses | pets | none------: | ---: | -----: | ---: | ---:      1 |    1 |      3 |    1 |    1

db<> fiddle here

关于mysql - 使用 having 添加一个新的选择字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54810845/

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