gpt4 book ai didi

mysql - 从按集合分组的值中选择值

转载 作者:行者123 更新时间:2023-11-29 01:19:39 25 4
gpt4 key购买 nike

我如何制作这个 SQL Fiddle从 GROUP BY 返回的元素子集中获取结果?

表格

CREATE TABLE IF NOT EXISTS `accounts` (
`master_id` int(3) unsigned NOT NULL,
`child_id` int(3) unsigned NOT NULL,
`name` varchar(200) NOT NULL
);

数据

INSERT INTO `accounts` (`master_id`, `child_id`, `name`) VALUES
('222', '555', 'child_555'),
('111', '111', 'master_111'),
('111', '999', 'child_999'),
('111', '888', 'child_888'),
('222', '222', 'master_222'),
('222', '777', 'child_777'),
('111', '666', 'child_666');

当前查询

SELECT 
master_id,
name,
count(*) as "Total Accounts"
FROM `accounts`
GROUP BY master_id ASC;

结果

+-----------+------------+-------+
| master_id | name | Total |
+-----------+------------+-------+
| 111 | master_111 | 4 |
| 222 | child_555 | 3 |
+-----------+------------+-------+

预期

 - Don't count child if child_id == master_id
- Get correct name

+-----------+------------+-------+
| master_id | name | Total |
+-----------+------------+-------+
| 111 | master_111 | 3 |
| 222 | master_222 | 2 |
+-----------+------------+-------+

最佳答案

我认为带有一些条件逻辑的简单聚合是最好的方法:

SELECT master_id,
MAX(CASE WHEN child_id = master_id THEN name END) as name,
SUM(child_id <> master_id) as "Total Accounts"
FROM `accounts`
GROUP BY master_id ASC;

Here是这个的 SQL fiddle 。

关于mysql - 从按集合分组的值中选择值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50484699/

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