简体   繁体   English

SUM对应于另一列

[英]SUM acorrding to another column

I need to know if there is a possible way doing this with out subquery.. 我需要知道是否有没有子查询的方法。

Here is my table structure: 这是我的表结构:

id-name-father_id
1  joe    0
2  mark   0
3  muller 0
4  miki   2
5  timi   2
6  moses  2
7  david  1
8  momo   0
9  daniel 0
10 ermi   3

My table logic is 我的表逻辑是

  • 0 means he is not a child of some one 0表示他不是某个孩子

  • 1+ mean that he is son of man in that row. 1+表示他是该行中的人子。

Note: if some one have a child, he still will have 0 in father id (it's mean there is not grand-fathers in my table) 注意:如果有人育有孩子,他的父亲ID仍为0(这意味着我的餐桌上没有祖父)

My query is : 我的查询是:

SELECT id, name, count(id=father_id) as sons
WHERE father_id = 0

What I want to get is a list of non-children (father_id=0) and sum the childrens it has. 我想非儿童的名单(father_id=0)sum它具有儿童。 Is there a way to get the results without a subquery? 有没有一种方法可以在没有子查询的情况下获得结果?

This should do it (MySQL): 这应该做到(MySQL):

SELECT `parents`.`id`, `parents`.`name`, COUNT(`children`.*) AS sons
FROM `people` AS parents
LEFT JOIN `people` AS children ON `parents`.`id` = `children`.`father_id`
WHERE `parents`.`father_id` = 0
GROUP BY `parents`.`id`

According to Gary we need to add name to GROUP BY in other SQL databases: Gary所说,我们需要在其他SQL数据库中为GROUP BY添加name

SELECT `parents`.`id`, `parents`.`name`, COUNT(`children`.*) AS sons
FROM `people` AS parents
LEFT JOIN `people` AS children ON `parents`.`id` = `children`.`father_id`
WHERE `parents`.`father_id` = 0
GROUP BY `parents`.`id`, `parents`.`name`

We are joing the table with itself here. 我们在这里自己摆桌子。 So we join all parents with their children. 因此,我们与所有父母一起带孩子。

This will lead to a result like that: 这将导致如下结果:

parents.id  parents.name children.id  children.name
1           joe          7            david
2           mark         4            miki
2           mark         5            timi
2           mark         6            moses
3           muller       10           ermi
8           momo         -            - # left join allows this line
9           daniel       -            -

But now we have each parent several times. 但是现在我们每个父母都有几次。 So we are GROUP'ing the whole thing over the parent's id, which will result in the following: 因此,我们正在将整个事情都放在GROUP ID上,而不是父母的ID,这将导致以下结果:

parents.id  parents.name COUNT(children.*)
1           joe          1
2           mark         3
3           muller       1
8           momo         0
9           daniel       0

You should be able to do it without any joins or sub-queries as follows: 您应该能够做到这一点而无需任何联接或子查询,如下所示:

select case father_id when 0 then id else father_id end id,
       max(case father_id when 0 then name end)     name,
       sum(sign(father_id))                         sons
from table
group by case father_id when 0 then id else father_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM