Aggregate function and other columns

2019-07-04 11:53发布

Is it possible for a SQL query to return some normal columns and some aggregate ones?

like :

Col_A | Col_B | SUM
------+-------+------
   5  |   6   |  7

标签: sql aggregate
5条回答
再贱就再见
2楼-- · 2019-07-04 12:09

Yes of course. Read on GROUP BY and aggregate functions. e.g.

SELECT col1, col2, SUM(col3) 
FROM table 
GROUP BY col1, col2
查看更多
叛逆
3楼-- · 2019-07-04 12:13

Yes, add them to GROUP BY clause.

查看更多
戒情不戒烟
4楼-- · 2019-07-04 12:17

You can show ordinary columns or expressions based on ordinary columns, but only if they are included in the set of columns/expressions you are agregating over ( what is listed in Group By clause ).

查看更多
地球回转人心会变
5楼-- · 2019-07-04 12:28

You should use the group by statement.

The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns.

For example:

SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name

You can see a complete example here.

查看更多
家丑人穷心不美
6楼-- · 2019-07-04 12:28

If you GROUP BY some fields, you can show those fields, and aggregate others; e.g.:

SELECT colA, colB, SUM(colC)
FROM TheTable
GROUP BY colA, colB

aggregation can be by SUM, MIN, MAX, etc.

查看更多
登录 后发表回答