Is it possible to have an SQL query that uses AGG functions in this way?

后端 未结 3 1671
孤城傲影
孤城傲影 2021-01-20 22:53

Assuming I have the following aggregate functions:

  • AGG1
  • AGG2
  • AGG3
  • AGG4

Is it possible to write valid SQL (in a db agnostic

3条回答
  •  礼貌的吻别
    2021-01-20 23:25

    The only way to aggregate over columns without using GROUP BY is to use windowing functions. You left out details of your problem, but the following might be what you are looking for:

    SELECT *
    FROM (
        SELECT [COL1, COL2 ....], 
               AGG1(param1) over (partition by some_grouping_column) as agg1, 
               AGG2(param2) over (partition by some_grouping_column) as agg2,
               row_number() over () as rn
        FROM [SOME TABLES]
        WHERE [SOME CRITERIA]
        ORDER BY COL1
    )  t
    WHERE AGG3 >-1 
      AND AGG4 < 123
      AND rn <= 10
    ORDER BY col1
    

    This is standard ANSI SQL and works on most database including PostgreSQL (since 8.4).

    Note that you do not need to use the same grouping column for both aggregates in the partition by clause.

    If you want to stick with ANSI SQL then you should use the row_number() function to limit the result. If you run this only on PostgreSQL (or other DBMS that support LIMIT in some way) move the LIMIT cause into the derived table (the inner query)

提交回复
热议问题