2015-10-06 119 views
0

我有兩個表具有這種結構:SQL SELECT COUNT(*)

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

謝謝!

+1

所以,這是一個直鏡頭真的: 'SELECT COUNT(column_names_desired)'對嗎?給它一點點 – Coffee

+1

你應該看看'GROUP BY'關鍵字 – Matthew

+1

是的,你需要一個「GROUP BY」 – Coffee

回答

3

我會傾向於unpivot的第二個表,然後再彙總:

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; 
+0

謝謝你這麼多戈登! – user3314399

1

如果我正確unterstand您的需要此查詢應符合您的期望:

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