仅对具有多行的组的值进行求和

时间:2017-12-13 11:25:10

标签: sql postgresql aggregate having

我有这个问题:

Font Book.app

结果如下:

enter image description here

只有当有多行SELECT extract(year from date1), extract(month from date1), spending FROM ( SELECT *, COUNT(*) OVER(PARTITION BY CONCAT(extract(year FROM date1), extract(month FROM date1))) N FROM table) as A WHERE N > 1 GROUP BY date1 ORDER BY date1 ASC; spending时,我才需要对字段year求和。期望的结果:

month

3 个答案:

答案 0 :(得分:0)

好的,我找到了解决方案:HAVING:

SELECT extract(year from date1), extract(month from date1), spending    
FROM table  
GROUP BY extract(month from date1)), extract(year from date1), extract(month from date1)
HAVING count (CONCAT(extract(year from date1), extract(month from date1))) > 1
ORDER BY extract(year from date1), extract(month from date1) ASC; 

以防万一。

答案 1 :(得分:0)

使用date_trunc()和一些简化可以更简单,更快捷:

SELECT date_trunc('month', date1)::date AS month
     , sum(spending)                    AS sum_spending
     , count(*)                         AS count_rows  -- optional addition
FROM   table
GROUP  BY 1
HAVING count(*) > 1
ORDER  BY 1;

仅返回多行的支出总和。

如果您需要显示单独的年份和月份数字,您可以在子查询中使用上述查询,但速度更快:

SELECT extract(year  FROM month)::int AS year
     , extract(month FROM month)::int AS month
     , sum_spending, count_rows
FROM (
   SELECT date_trunc('month', date1)::date AS month
        , sum(spending)                    AS sum_spending
        , count(*)                         AS count_rows  -- optional
   FROM   table
   GROUP  BY 1
   HAVING count(*) > 1
   ORDER  BY 1
   ) sub;

或者直接在解决方案中提取数字,但只需在count(*)子句中使用更快HAVING

SELECT extract(year  FROM date1)::int AS year
     , extract(month FROM date1)::int AS month
     , sum(spending)                  AS sum_spending
     , count(*)                       AS count_rows  -- optional
FROM   table
GROUP  BY 1, 2
HAVING count(*) > 1
ORDER  BY 1, 2;

1, 2是(完全可选的)位置引用以缩短语法,因此我们不必重复SELECT列表中的表达式。例如:

强制转换为整数(::int)也是可选的。提取的泛型返回类型是双精度,但年和日期可以安全地转换为整数。更小,更快,更充足。

答案 2 :(得分:0)

试试这个

SELECT extract(year from date1), extract(month from date1), sum(spending)    
FROM ( SELECT *, COUNT(*) OVER(PARTITION BY CONCAT(extract(year FROM date1), extract(month FROM date1))) N
       FROM table) as A    
WHERE N > 1    
GROUP BY extract(year from date1),extract(month from date1)
ORDER BY extract(year from date1),extract(month from date1) ASC;