Here we have Simple basic table structure same as of Emp dept tables available in Oracle .
Here we need to Find the total number of employees working in Department. I am adding various alternate ways of doing this task.
Table Employee Data Structure
Id | Name | DeptId |
---|---|---|
1 | A | 10 |
2 | B | 10 |
3 | C | 10 |
4 | D | 10 |
5 | E | 20 |
6 | F | 20 |
7 | G | 20 |
8 | H | 30 |
9 | I | 30 |
Table Department Data Structure
DeptId | Name |
---|---|
10 | Sales |
20 | Dev |
30 | Tester |
Expected Output
Id | Name | DeptId | Count |
---|---|---|---|
1 | A | 10 | 4 |
2 | B | 10 | 4 |
3 | C | 10 | 4 |
4 | D | 10 | 4 |
5 | E | 20 | 3 |
6 | F | 20 | 3 |
7 | G | 20 | 3 |
8 | H | 30 | 2 |
9 | I | 30 | 2 |
Create table Query
SELECT * INTO SQL16 FROM ( SELECT 1 id , 'A' name , 10 deptid UNION ALL SELECT 2 , 'B' , 10 UNION ALL SELECT 3 , 'C' , 10 UNION ALL SELECT 4 , 'D' , 10 UNION ALL SELECT 5 , 'E' , 20 UNION ALL SELECT 6 , 'F' , 20 UNION ALL SELECT 7 , 'G' , 20 UNION ALL SELECT 8 , 'H' , 30 UNION ALL SELECT 9 , 'I' , 30 ) t
Alternate Solution 1
SELECT * INTO SQL16_1 FROM ( SELECT 10 id , 'Sale' Dname UNION ALL SELECT 20 , 'Dev' UNION ALL SELECT 30 , 'QA' ) t1
Alternate Solution 2SELECT ID , NAME , DEPTID , COUNT(*) OVER ( PARTITION BY DEPTID ORDER BY DEPTID ) AS CUMMULATIVE_SUM FROM SQL16;
Alternate Solution 3SELECT ID , NAME , DEPTID , ( SELECT SUM(1) CUMMULATIVE_SUM FROM SQL16 CI WHERE CI.DEPTID = CO.DEPTID GROUP BY DEPTID ) AS CUMMULATIVE_SUM FROM SQL16 CO;
Alternate Solution 4SELECT CO.ID , CO.NAME , CO.DEPTID , ( CASE WHEN CI.DEPTID = CO.DEPTID THEN SUM(1) OVER ( PARTITION BY CO.DEPTID ORDER BY CO.DEPTID ) END ) AS CUMMULATIVE_SUM FROM SQL16 CO JOIN SQL16 CI ON CO.ID = CI.ID;
Alternate Solution 5SELECT * FROM SQL16 p14 LEFT JOIN ( SELECT count(*) cnt , deptid FROM SQL16 GROUP BY deptid ) t1 ON t1.deptid = p14.deptid
No comments:
Post a Comment