仅对具有多行的组求和值

Only sum values for groups with more than one row

我有这个查询:

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;

结果如下:

只有当 equla yearmonth 超过一行时,我才需要对字段 spending 求和。期望的结果:

year    month   spending
----    -----   --------
2015     1        5424
2016     1      605886
2016     5      xxxxxx
....     ..     ......

好的,我找到了解决方案: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; 

以防对某人有帮助。

使用 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;

只有 returns 超过一行的月份的支出总和。

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

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;

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

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 列表中的表达式。示例:

  • Select first row in each GROUP BY group?

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

试试这个

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;