迭代行SQL + Count

时间:2015-06-17 20:14:38

标签: sql sql-server tsql

我有一个包含许多列和行的表,并且一列下有组,另一列下有人,每组中可以有一个或多个人。我想做这样的事情(伪代码):

if there is more than one instance of that group showing up:
    iterate through it and count how many members in that group have family members, then insert into a table
else:
    just take out that member and count how many family members he has and insert into a table

我来自python背景,SQL对我来说仍然是一个新手,但我的(非常糟糕)尝试:

if (select count(groupname) from table group by groupname) > 1 
then _________
else
insert___ into ___

表A看起来有点像这样:

groups                   people
A                        tom
A                        jerry
B                        sarah

表B如下所示:

person                   familyMembers
tom                        daughter
tom                        son
tom                        wife
sarah                      husband

汤姆有3个家庭成员,莎拉只有1个

有点失落,见解?

1 个答案:

答案 0 :(得分:0)

有点不清楚该组织如何发挥作用。听起来你想要计算每个人的家庭成员数量,对吗?一种简单的方法是在tableB中计算族:

SELECT
  person,
  COUNT(familyMembers) AS count_familyMembers
FROM tableB
GROUP BY person

这忽略了" group"列一起,但如果他们没有在tableB中有记录(例如你的例子中的Jerry),将会错过任何人。

要包括Jerry,您需要执行以下操作。这将检查familyMembers是否为NULL并返回0,否则将返回1.然后将所有这些加起来,这样就可以得到记录总数,按组和人员列分开。

SELECT
  groups,
  people,
  SUM(CASE
    WHEN familyMembers IS NULL THEN 0
    ELSE 1
  END) AS count_familyMembers
FROM tableA
LEFT JOIN tableB
  ON tableA.people = tableB.person
GROUP BY groups,
         people

如果上述方法有效,您可以添加" INTO"创建一个新表:

SELECT
  groups,
  people,
  SUM(CASE
    WHEN familyMembers IS NULL THEN 0
    ELSE 1
  END) AS count_familyMembers INTO new_table
FROM tableA
LEFT JOIN tableB
  ON tableA.people = tableB.person
GROUP BY groups,
         people

或" INSERT INTO"对于现有表格。如果您执行了#34; INSERT INTO",则需要匹配数据和列:

INSERT INTO existingTable (groups, people, familyCount)
  SELECT
    groups,
    people,
    SUM(CASE
      WHEN familyMembers IS NULL THEN 0
      ELSE 1
    END) AS count_familyMembers INTO new_table
  FROM tableA
  LEFT JOIN tableB
    ON tableA.people = tableB.person
  GROUP BY groups,
           people