'Getting max,sum,count... funciton results for columns in form of a table

Let's assume we have a table below having many rows and 4 columns A,B,C, D


+---+----+---+---+
| A |  B | C | D |
+---+--------+---+
| 1 | 1 | 1 |  2 |
| 2 | 2 | 2 |  2 |
| 3 | 3 | 3 |  2 |
| . | . | . |  . |
| . | . | . |  . |
+---+---+---+----+

Now I want the result in the form of a table like below using sql


+---------------+----------------+----------------+------------------+
|       A       |        B       |       C        |         D        |
+---------------+----------------+----------------+------------------+
| max(columnA)  | max(columnB)   | max(column C)  |  max(Column D)   |
| count(columnA)| count(columnB) | count(column C)|  count(Column D) |
| sum(columnA)  | sum(columnB)   | sum(column C)  |  sum(Column D)   |
+---------------+----------------+----------------+------------------+

I know this can be done using something shown below but is there a different way of doing it? The table I'm working on is a bit large and there are multiple functions which I would have to apply on it therefore the select query would be big and there would be multiple union statements, so is there a way to avoid it using 'union' method? Thank you for your help.


select max(A),max(b), max(c),max(d) from table where ...
UNion
select count(A),count(B),count(c),count(d) from table where ...
union
.
.


Solution 1:[1]

Use a CTE:

with summary as (
    select
        max(a) max_a,
        max(b) max_b,
        max(c) max_c,
        max(d) max_d,
        count(a) count_a,
        count(b) count_b,
        count(c) count_c,
        count(d) count_d,
        sum(a) sum_a,
        sum(b) sum_b,
        sum(c) sum_c,
        sum(d) sum_d
    from mytable
    -- optional joins, where clause, etc
)
select max_a a, max_b b, max_c c, max_d d from summary
union all
select count_a, count_b, count_c, count_d from summary
union all
select sum_a, sum_b, sum_c, sum_d from summary

Note the use of union all, which preserves duplicate rows, rather than union, which removes duplicates (although duplicates would be very unlikely here).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bohemian