Click here to Skip to main content
15,880,967 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi Guys ,

Today I went to Interview for SQL developer.He asked me one question ,after long struggle to gave up my self from there

lets talk about query
I have Employee table

empId  ename   deptId
1      P       10
2      Q       10
3      X       20
4      Y       20
5      Z       20
6      P1      10
7      Q1      10
8      X1      20
9      Y1      20
10     Z1      20
11     m       30

and Certification table

certId  empid
1        1
2        3
3        5
4       11

Now he wants the dept Id on which doesn't have 50% of certification done by their employees

output :

Dept ID 
10
20 


I tried by with below query

SQL
Select a.deptID from
(Select COUNT(*)as  total ,deptId
 from #employee
Group by deptId) A
join
 (Select COUNT(*) as deptwise ,deptId
                        from  #employee emp left join #certifiaction cert
                        on  cert.empid=emp.empid
                        where  cert.certId is null
                        group by emp.deptId) B

ON A.deptId=B.deptId
where (b.deptwise*0.1) /(a.total*0.1)>0.5


But he doesn't want this query.How to do that with out doing derived tables?

Please help me to resolve ,will help for another interview .


Thanks
Pratap
Posted
Updated 6-Mar-15 22:48pm
v4

1 solution

Try this:
SQL
WITH CTE0 (deptid, deptcount)
AS
(
   select e1.deptid, count(c.empid)
   from employee e1 join certificate c on e1.empid = c.empid
   group by e1.deptid
),
CTE1 (deptid, deptcount)
AS
(
   select deptid, count(empid)
   from employee
   group by deptid
)
SELECT CTE1.deptid FROM cte0 join cte1 ON CTE0.deptid=CTE1.deptid WHERE
CTE0.deptcount / CTE1.deptcount < 0.5

refer: Common Table Expressions(CTE) in SQL SERVER 2008[^]
 
Share this answer
 
v2
Comments
Member 11283674 7-Mar-15 5:59am    
Thanks Peter.But interviewer asked me to use count over partitioned by clause and achieve it in a single step.
Jörgen Andersson 7-Mar-15 6:37am    
The function they're after is probably ntile
Member 11283674 7-Mar-15 6:51am    
How does NTILE function come into picture in this scenario.Can you
please elaborate

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900