从按组分组中选择值

时间:2018-05-23 09:29:14

标签: mysql sql

如何从GROUP BY返回的元素子集中获取此SQL Fiddle结果?

表格

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 |
+-----------+------------+-------+

6 个答案:

答案 0 :(得分:3)

我认为使用某些条件逻辑的简单聚合是最好的方法:

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小提琴。

答案 1 :(得分:2)

SELECT 
b.master_id, 
a.name,
count(*) as "Total Accounts"
FROM accounts b, accounts a
where b.master_id<>b.child_id
and a.child_id = b.master_id
GROUP BY b.master_id ASC;
或者正如M Khalid Junaid所说:

SELECT 
  b.master_id,
  a.name,
  COUNT(*) AS "Total Accounts" 
FROM
  accounts b 
  JOIN accounts a 
    ON b.master_id <> b.child_id 
    AND a.child_id = b.master_id 
GROUP BY b.master_id ASC 

结果:

master_id   name        Total Accounts
111         master_111  3
222         master_222  2

答案 2 :(得分:1)

使用case表达式执行条件聚合:

select b.master_id, a.name, 
       sum(case when b.master_id <> b.child_id then 1 else 0 end) as "Total Accounts"
from `accounts` a
inner join `accounts` b on a.child_id = b.master_id
group by b.master_id 
order by b.master_id ASC; 

但是,WHERE条款也应该做。

select master_id, name, 
       count(*) as "Total Accounts"
from `accounts`
where master_id != child_id
group by master_id 
order by master_id ASC; 

答案 3 :(得分:0)

这是一个没有自我加入的解决方案

g.V(123).valueMap(True).toList()

DEMO

答案 4 :(得分:0)

select master_id, name, 
       sum(master_id != child_id) as Total
from `accounts`
group by master_id 
order by master_id ASC; 

Demo on SQL Fiddle

答案 5 :(得分:0)

试试这个......

SELECT master_id, name, count(*) as "Total Accounts" 
FROM accounts where master_id != child_id
GROUP BY master_id ASC;