2017-01-11 68 views
1

加入我需要在我的桌子的底部添加一個。這是可能的在我的情況?共在底部

select country, count(*) from customer 
group by country 

Country   Count 
    USA    5 
    UK    10 
Canada   15 
Russia   25 
        55 (Requested from SO community) 
+0

是否有可能爲錶行越來越大?或者他們會保持不變? –

+0

保持相同@ Hawraa。 –

回答

4

使用rollup()

select country, count(*) 
from customer 
group by rollup (country) 

行,您可以使用grouping功能:

select case 
      when grouping(country) = 1 then 'Total' 
      else country 
     end as country, 
     count(*) 
from customer 
group by rollup (country) 

在線例如:http://rextester.com/PKFE63954

2

可以人爲地通過使用像

select country 
    ,count(*) 
from customer 
group by country 

UNION ALL 

SELECT 'Total' 
    ,COUNT(*) 
FROM customer 

東西雖然這會影響你做出這個結果集的任何將來的計算,因爲它是在數據的新行生成一行。

+0

您也可以將另一列添加到名爲Total的行。 DECLARE @Total int = 0; SET atTotal = SELECT COUNT(*)FROM customer SELECT country,COUNT(*),atTotal FROM customer GROUP BY country –

+0

@Musters,我可以在哪裏得到這個代碼? –

+0

我會做出這個答案,評論是不好的... –

2

類似:

SELECT country 
    , count(´1) 
FROM customer 
GROUP BY country 

UNION 

SELECT 'TOTAL' 
    , count(1) 
FROM customer; 
+0

感謝Moe,雖然它返回了總計函數的總數,但它將俄羅斯之前的Total計算在底部。你對此有何見解? –

+0

您可以添加反向標識(ID),以第一個SELECT語句,然後在第二個SELECT語句設定的ID = 0,終於到了聯盟的聲明,對ID添加一個ORDER BY子句。 –

+1

是的,你是對的@JasonSmith,只是改變「聯盟」爲「UNION ALL」 – Jay

-1

你可以如果你想標籤 「總」 以及另一列添加到名爲總

 DECLARE @Total int = 0; 
     SET @Total = (SELECT COUNT(*) FROM customer); 

     SELECT country, COUNT(*), [Total] = @Total 
     FROM customer 
     GROUP BY country 
+0

召集它拋出了一個錯誤的@ !!!! –

+0

這是無效的Postgres的(和無效的標準SQL) –

+0

忘記括號,更新的答案 –