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

问题描述 投票:1回答:3

我有这个问题:

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;

有了这个结果:

enter image description here

我需要将字段spending求和,只有当有一个以上的行时才能使用equla yearmonth。期望的结果:

year    month   spending
----    -----   --------
2015     1        5424
2016     1      605886
2016     5      xxxxxx
....     ..     ......
sql postgresql aggregate having
3个回答
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; 

万一它可以帮助某人。


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)也是可选的。提取的泛型返回类型是双精度,但年和日期可以安全地转换为整数。更小,更快,更充足。


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;
© www.soinside.com 2019 - 2024. All rights reserved.