2012-12-12 19 views
7

是否有任何方法可以使第一行與其他行不同?因此它會顯示相應列的總和?PostgreSQL - 使第一行顯示爲其他行的總數

例如:

 fruits|a|b|c 
     total|3|4|6 
     apples|1|2|3 
    bananas|1|1|2 
    oranges|1|1|1 

是否有可能使查詢一樣,或者是針對SQL的邏輯是什麼? 這將是這樣的(現在忽略的第一行):

SELECT fruits, sum(a), sum(b), sum(c) 
FROM basket 

所以第一行會有所不同。它將顯示單詞'total'而不是水果名稱,並且將顯示a(1 + 1 + 1 = 3),b(2 + 1 + 1 = 4)和c(3 + 2 + 1 = 6) 。是否有可能這樣做?由於

+0

你可以簡單的'UNION ALL'這兩個查詢(可能你也必須施放你的值)。 – dezso

+0

[Postgres:選擇值的總和,然後再總結這個]的可能重複(http://stackoverflow.com/questions/12070855/postgres-select-the-sum-of-values-and-then-sum-this -again) –

回答

17

可以避開表與CTE第二全掃描:

的PostgreSQL 9.2架構

create table basket(fruits text, a integer, b integer, c integer); 
insert into basket(fruits, a, b, c) values('apples', 1, 1, 1), 
              ('apples', 0, 1, 2), 
              ('bananas', 1, 1, 2), 
              ('oranges', 1, 1, 1); 

查詢

with w as (select fruits, sum(a) a, sum(b) b, sum(c) c 
      from basket 
      group by fruits) 
select * from w union all select 'total', sum(a), sum(b), sum(c) from w 

結果

| FRUITS | A | B | C | 
----------------------- 
| bananas | 1 | 1 | 2 | 
| oranges | 1 | 1 | 1 | 
| apples | 1 | 2 | 3 | 
| total | 3 | 4 | 6 | 

SQL小提琴here

+0

謝謝。這更好。 – Andrius

+0

謝謝。我喜歡postgres,但這個問題讓我期待['rollup'](http://docs.oracle.com/cd/E11882_01/server.112/e26088/statements_10002.htm#SQLRF55331)這是一種更自然的方式這樣做。 – 2012-12-13 10:51:36

5
SELECT 'total' AS fruits, sum(a), sum(b), sum(c) FROM basket 
UNION ALL 
SELECT fruits, sum(a), sum(b), sum(c) FROM basket GROUP BY fruits 
+0

感謝您的解決方案 – Andrius

7

This is now possible in version 9.5 of Postgres

的PostgreSQL 9.5架構

CREATE TABLE basket(fruits text, a integer, b integer, c integer); 
CREATE TABLE 
INSERT INTO basket(fruits, a, b, c) values('apples', 1, 1, 1), 
             ('apples', 0, 1, 2), 
             ('bananas', 1, 1, 2), 
             ('oranges', 1, 1, 1); 

查詢

SELECT coalesce(fruits,'total'), sum(a) a, sum(b) b, sum(c) c 
FROM basket 
GROUP BY ROLLUP((fruits)) 

結果

fruits | a | b | c 
---------+---+---+--- 
apples | 1 | 2 | 3 
bananas | 1 | 1 | 2 
oranges | 1 | 1 | 1 
total | 3 | 4 | 6 

ROLLUP等同於使用的表達與GROUPING SETS

SELECT fruits, sum(a) a, sum(b) b, sum(c) c 
FROM basket 
GROUP BY GROUPING SETS (fruits,()) 

GROUPING SETS每個子列表被解釋的方式相同,雖然它直接在GROUP BY cl中澳洲英語。