我在使用值集合时遇到麻烦。我的表看起来像这样:
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的DISTINCT ID
Register_count: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;
有什么想法吗?
答案 0 :(得分:1)
<强> SQL DEMO 强>
WITH t_count as (
SELECT f.date, COUNT(DISTINCT f.actifs), COUNT(DISTINCT f.registers)
FROM
(
SELECT unnest(a_actif) as actifs,
a_date as date,
unnest(a_registred) as registers
FROM test2
WHERE a_filter IN ('1','2','3','5')
) f
--WHERE date BETWEEN '2016-09-01' AND '2016-09-01'
GROUP BY f.date
), t_sum as (
SELECT a_date as date, SUM(sum_actions) total
FROM test2
WHERE a_filter IN ('1','2','3','5')
--WHERE date BETWEEN '2016-09-01' AND '2016-09-01'
GROUP BY date
)
SELECT t1.*, t2.total
FROM t_count t1
JOIN t_sum t2
ON t1.date = t2.date
输出