2013-10-12 25 views
5

我通常通過psycopg2執行中的PostgreSQL 9.1順序如下SQL查詢每隔幾秒鐘:PostgreSQL的多個計數(),其中在一個單一的查詢條件

select count(type) from bag where type= 'fruit'; 
select count(type) from bag where type= 'vegtable'; 
select count(type) from bag where type= 'other'; 
select count(type) from bag where type= 'misc'; 

是否有可能做同樣的事情在一個單一的選擇查詢,以便即使該計數爲零,我也可以獲得每種類型的計數。如果給定的類型有零時,它給了我零計數,下面的工作將會起作用。

select type, count(*) from bag group by type; 

謝謝

回答

4

使用派生表作爲查詢的錨:

select a.type, count(b.type) 
from (values ('fruit'), ('vegtable'), ('other'), ('misc')) as a(type) 
    left outer join bag as b on b.type = a.type 
group by a.type 

sql fiddle demo

+0

我在最後按類型拋出了一個命令,這正是我想要的。謝謝。 – user2695222

1

可以有很多這種可能的解決方案。一種是通過使用UNION ALL在子查詢中生成所有期望的類型,並針對bag表執行LEFT JOIN。在這種情況下,您想獲得的所有types將顯示在結果列表中,表bag上的不存在類型將具有零計數。這將會在差不多工作在所有RDBMS上。

SELECT a.type, 
     COUNT(b.type) TotalCount 
FROM 
     (
      SELECT 'fruit' AS type UNION ALL 
      SELECT 'vegtable' AS type UNION ALL 
      SELECT 'other' AS type UNION ALL 
      SELECT 'misc' AS type 
     ) AS a 
     LEFT JOIN bag AS b 
      ON a.type = b.type 
GROUP By a.type 
+0

感謝幫助。謝謝 – user2695222

相關問題