SQL Select和Count语句

时间:2015-11-15 10:29:57

标签: sql sql-server

我有一张表如下

 --------------------------------
 ChildId | ChildName | ParentId |
 --------------------------------
    1    |     A     |    0     |
 --------------------------------
    2    |     B     |    1     |
 --------------------------------
    3    |     C     |    1     |
 --------------------------------

我想选择数据 -

 ---------------------------------------
     Id   |    Name    |     Childs    |
 ---------------------------------------
     1    |      A     |       2       |
 ---------------------------------------
     2    |      B     |       0       |
 ---------------------------------------
     3    |      C     |       0       |
 ---------------------------------------

伪SQL语句应该是这样的 -

SELECT ChildId AS Id, ChildName as Name, (Count (ParentId) Where ParentId=ChildId)

任何帮助?

3 个答案:

答案 0 :(得分:2)

这样可以解决问题:

select t1.childid, t1.childname, count(*) as childs
from table t1
join table t2 on t1.childid = t2.parentid
group by t1.childid, t1.childname

答案 1 :(得分:0)

如果只有一个级别,您可以在伪代码中使用该方法。它应该是这样的:

SELECT 
    ChildId AS Id, 
    ChildName as Name, 
    (select Count(ParentId) from t t_inner Where ParentId=t_outer.ChildId) children
from t t_outer
-- optionally where clause to limit result to parents that have children
where exists (select 1 from t where ParentId in (t_outer.ChildId))

但是如果你想要父母的子女总数(包括孙子女等),你可以使用递归查询解决这个问题。

答案 2 :(得分:0)

这样的东西?

   <Button
        style="?android:attr/buttonBarButtonStyle"
        android:layout_width="0dp"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:text="^"
        android:background="#c6010101"
        android:textColor="#FFFFFCFC" />

但是这将为您提供所有节点以及不应成为层次结构一部分的子节点

如果您只想要有子节点的节点,请使用cte

SELECT ChildId AS Id, ChildName as Name, (SELECT COUNT(*)  FROM TestCountOver T WHERE T.ParentID = O.ChildID) FROM TestCountOver O