2014-10-20 44 views
0

是否有一種更簡單的方法來計算滿足相同條件的不同表中的行數?對多個表進行條件計數

例如,我要單獨計算行的下面兩個表中分別對應特定的ID的數量的:

Select 
'table1' as tablename, count(*) as rownr from table1 
where SOMEID in ('1815972751','1815751159','1815752967','1815756079') 

union all 

Select 
'table2' as tablename, count(*) as rownr from table2 
where SOMEID in ('1815972751','1815751159','1815752967','1815756079') ; 

結果會是這樣的

table1 | 21 
table2 | 54 

然而,我只想定義條件(在這種情況下,ID)一次,例如在一個變量或列表中,因此它們的區域易於管理。

回答

2

這裏有一種方法:

select tablename, count(*) 
from (select 'table1' as tablename, someid 
     from table1 
     union all 
     select 'table2' as tablename, someid 
     from table2 
    ) t 
where someid in ('1815972751', '1815751159', '1815752967', '1815756079') 
group by tablename; 

請注意,性能可能不如在你原來的版本一樣好。

+0

謝謝,作品像魅力! – Cos 2014-10-20 15:45:37

相關問題