0
我在聚合時遇到值問題。我的表是這樣的:在postgres中聚合多個列
CREATE TABLE test2 (a_date date, a_actif integer[], a_registred integer[], a_filter integer, sum_actions integer);
INSERT INTO test2 VALUES
('2016-12-15', array[1,2,3], array[1,4], 5, 2),
('2016-12-15', array[5], array[1,4], 2, 20),
('2016-12-15', array[6,2,3], array[2,3], 3, 10),
('2016-12-15', array[8,2,3], array[4,1], 1, 4);
目標是算上不同a_actif和a_registred,並獲得總和,每日期,動作的數量。 這應該是這樣的:
-----------------------------------------------------------
| Date | Active_count | Register_count | sum_actions |
-----------------------------------------------------------
|2016-12-15| 6 | 4 | 36 |
-----------------------------------------------------------
Active_count:a_actif
Register_count的DISTINCT ID:的a_registred
所以我做了這樣的事情DISTINCT ID,但行動的總和是錯誤的
SELECT f.date, COUNT(DISTINCT f.actifs), COUNT(DISTINCT f.registers), SUM(sum_actions)
FROM
(
SELECT unnest(a_actif) as actifs, a_date as date, unnest(a_registred) as registers, sum_actions
FROM test2
WHERE a_filter IN ('1','2','3','5')
) f
--WHERE date BETWEEN XX and YY
GROUP BY f.date;
任何想法?
檢查你的''unnest'without組by' http://rextester.com/OTMU9161是顯然你爲什麼得到錯誤的總和。只需在分開的子查詢中計算總和即可。讓我知道是否需要更多的指導方針 –