Friday, March 30, 2012

Problem in inner join ?

Hai ,

select emp_id,count(emp_id) as count1 from poll_data group by emp_id order by count1 desc

The output of above query is

emp_id count1

EMP10041 8
EMP10058 8
EMP10059 6
EMP10008 6
EMP10012 3
EMP10018 3
EMP10039 3
EMP10001 2

I have another table as user_table

user_id user_name

EMP10001 Raja
EMP10039 Ram
EMP10018 Ravi

etc

now i am writing a inner join as follows

select y.user_name, x.count1 from [select emp_id,count(emp_id) as count1 from poll_data group by emp_id order by count1 desc] x inner join [user_table] y on x.emp_id = y.user_id

I want to get the below format

Jambu 8
Elangovan 8
Ravi 6
Anitha 6
Ram 3

but i am getting the below error :

Invalid object name 'select emp_id,count(emp_id) as count1 from poll_data group by emp_id order by count1 desc

how to solve this

remove the [ ] & order by clasue on the sub query. Sub query should be enclosed with ( ).

Code Snippet

select

y.user_name

, x.count1

from

(select emp_id,count(emp_id) as count1 from poll_data group by emp_id) x

inner join [user_table] y on x.emp_id = y.user_id

|||

You need to enclose the derived table in parentheses -NOT square brackets.

Code Snippet


SELECT
u.User_Name,
p.Count1
FROM (SELECT
Emp_ID,
Count1 = count(Emp_ID)
FROM Poll_Data
GROUP BY Emp_ID
) p
INNER JOIN User_Table u
ON p.Emp_ID = u.User_ID

No comments:

Post a Comment