I'm currently using postgres for a datawarehouse and are running into some big queries which are set up the following way:
SELECT
col_1,
col_2,
col_3,
...,
col_41,
SUM(col_42)
FROM table
GROUP BY
1,2,3,4,..., 41
I'm not fond of the group by syntax using the numbers, but with the sheer number of columns I can see why it would be used.
My main question is: Is there a way to simply group by all columns without an aggregating function?
Something along the lines of:
SELECT
col_1,
col_2,
col_3,
...,
col_41,
SUM(col_42)
FROM table
GROUP BY ALL
or even
SELECT
col_1,
col_2,
col_3,
...,
col_41,
SUM(col_42)
FROM table
GROUP BY 1 to 41
would be an improvement.
You can almost do what you want . . . if you are content to have the first column be a tuple rather than a column reference:
SELECT (col1, col2, col3), SUM(x)
FROM t
GROUP BY 1
I don't think there is a way to extract the columns from a tuple without listing them. For instance, the following does not work:
SELECT t.cols.*, sum_x
FROM (SELECT (col1, col2, col3) as cols, SUM(x) as sum_x
FROM t
GROUP BY 1
) t;
You can reconstruct the columns -- but you are back to verbosity. For an anonymous row type:
SELECT (cols).f1 as col1, (cols).f2 as col2, (cols).f3 as f3, sum_x
FROM (SELECT (col1, col2, col3) as cols, SUM(x) as sum_x
FROM t
GROUP BY 1
) t;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.