多列中的SQL COUNT

时间:2015-12-10 14:51:55

标签: mysql sql

我想知道SQL是什么,如果我希望数据从数字的出现相对于另一个表中的数据计算。

TABLE1

Day1         Day2
--------------------
1            2
2            3
1            3
3            1

TABLE2

ID       NAME
------------------
1        John
2        Mary
3        Tom

我希望SQL的结果是这个

ID       NAME        OCCUR
1        John        3
2        Mary        2
3        Tom         3

获取此结果的SQL如何?

4 个答案:

答案 0 :(得分:2)

似乎您想要计算table1中有多少行在任一列中都有匹配值。一个简单的方法是:

select t2.*,
       (select count(*)
        from table1 t1
        where t2.id in (t1.day1, t1.day2)
       ) as occur
from table2 t2;

答案 1 :(得分:0)

在表1中,您必须为表格2创建外键。可能是用户的ID。有了这个:

Select t2.id, t2.name, Sum(t1.day) 
from table1 t1
innerjoin table2 t2 
on t1.id = t2.id

答案 2 :(得分:0)

从table2中选择id和name,并在子查询中获取table1中出现的次数:

select 
  id, 
  name, 
  (
    select sum
    (
      case when t1.day1 = t2.id then 1 else 0 end +
      case when t1.day2 = t2.id then 1 else 0 end
    )
    from table1 t1
    where t2.id in (t1.day1, t1.day2)
  ) as occur
from table2 t2

答案 3 :(得分:0)

day1day2列合并为一,然后计数。

<强>查询

select t1.ID, t1.Name, count(t2.[day]) as occur
from table2 t1
left join 
(select Day1 as [day] from table1
union all 
select Day2 as [day] from table1) t2
on t1.ID = t2.[day]
group by t1.ID, t1.Name;
相关问题