简体   繁体   中英

Oracle SQL Rollup Query : Determine the start of group

How can we determine the start of a Group in Rollup ? And the include the group value by concatinating it with some useful text and display it as first row of the group ?

eg:

dept   emp_name sal
----   -------- ---
10     sac      999
10     abc      888
20     pqr      777
20     lmn      123
30     stv      444
30     com      555

o/p after rollup should be

dept             emp_name sal
----             -------- ---
Department 10    NULL     NULL
10               sac      999
10               abc      888
20                        1887   
Department 20    NULL     NULL
20               pqr      777
20               lmn      123
20                        900 
Department 30    NULL     NULL
30               stv      444
30               com      555
30                        999
                          3786

Here is the query with which you can achieve the requirement. It uses GROUP BY ROLLUP

SELECT DISTINCT 1 AS rn,dept, CONCAT('Department ',  dept) AS DeptDesc, NULL AS Sum
  FROM your_table 
UNION ALL
SELECT 2, dept, CAST(dept AS VARCHAR(10)), SUM(SAL)
  FROM your_table
GROUP BY ROLLUP(dept, emp_name)
ORDER BY dept, rn, sum  

Here is the code at SQL Fiddle

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM