SQL选择计数(*)

时间:2015-10-06 20:57:54

标签: sql sql-server sql-server-2008

我有两个具有这种结构的表:

TABLE_1:

Column_A(P_Key)    Column_B
  Val1             Location1
  Val2             Location1
  Val3             Location2
  Val4             Location3
  Val4             Location4
  Val4             Location5

TABLE_2:

   Column_A(P_Key)    Column_B   Column_C
   Location1          Person_1    Person_2
   Location2          Person_1    Person_3
   Location3          Person_3    Person_4
   Location4          Person_1    Person_5
   Location5          Person_2    Person_3

我需要一个查询来计算每个人在每个位置负责的项目数量:

例如,查询应返回:

Person     Total
Person_1     4
Person_2     3
Person_3     3
Person_4     1
Person_5     1

这适用于SQL Server 2008 R2

谢谢!

2 个答案:

答案 0 :(得分:3)

我倾向于将第二张表格取消,然后重新汇总:

select person, count(*)
from ((select column_b as person
       from table2 t2 join
            table1 t1
            on t2.column_a = t1.column_b
      ) union all
      (select column_c as person
       from table2 t2 join
            table1 t1
            on t2.column_a = t1.column_b
      )
     ) p
group by person
order by count(*) desc;

答案 1 :(得分:1)

如果我正确地了解您的需求,此查询应符合您的期望:

SELECT DISTINCT t.column_a AS person,
    (SELECT COUNT(*) FROM table_2 t1 WHERE t1.column_b = t.column_a) + (SELECT COUNT(*) FROM table_2 t2 WHERE t2.column_c = t.column_a) AS Total
FROM
    table_2 t