Oracle, according to grouping data statistics, total and sorting

The data stored in Table A is some area data, and these data have different types.

The data stored in table B is the type dictionary of table A data.

Requirement: After performing statistics based on types, perform total calculations.

sql:

SELECT
  CASE WHEN GROUPING ( B.F_NAME ) = 1 THEN'合计' ELSE B.F_NAME END AS Name,
	B.f_code code,
	ROUND( SUM( A.AREA_SYQ ) / 100, 2 ) AREA 
	FROM
	( SELECT F_NAME, f_code FROM B WHERE F_YEAR = '2019' AND F_TYPE = '01' ) B
	JOIN A ON A.F_NAME = A.DL_NAME 
	GROUP BY rollup ((B.F_NAME,B.f_code )) 
ORDER BY
	B.f_code Nulls first //根据code进行排序,若遇到null值则放到第一位

result:

Functions used:

GROUPING(): Generate an additional column. When a row is added with the CUBE or ROLLUP operator, the output value of the additional column is 1. When the added row is not generated by CUBE or ROLLUP, the value of the additional column is 0. That is, if the parameter in GROUPING is not in the database, an int type data 1 will be returned;

ROUND(): is to round the data;

rollup(): It is an extended function of group by. The initial feeling is that you can group by multiple columns and then perform statistics separately. Specific introduction: rollup clause summary

Guess you like

Origin blog.csdn.net/qq_36802726/article/details/103784982
Recommended