Wednesday, 11 September 2013

problems while trying to optimize my SQL(inner join and group)

problems while trying to optimize my SQL(inner join and group)

Im having a problem in joining and grouping two table. Im using ms sql
server 2005 express .
table1 : ot
date_request | requested_by | status | approved_by |
09/10/2013 xxx A admin1
09/10/2013 yyy A admin1
09/10/2013 zzz A admin1
09/11/2013 xxx A admin2
09/11/2013 yyy A admin1
09/11/2013 zzz A admin2
table2 : otd
userid | task | date_request |
xxx 1 09/10/2013
xxx 2 09/10/2013
yyy 3 09/10/2013
yyy 4 09/10/2013
zzz 0 09/10/2013
zzz 2 09/10/2013
zzz 4 09/10/2013
xxx 5 09/11/2013
xxx 6 09/11/2013
and my sql statement :
SELECT otd.userid,otd.task,otd.date_request,ot.approved_by
FROM otd INNER JOIN ot ON otd.userid = ot.requested_by
WHERE otd.userid ='xxx'
AND CONVERT(varchar,otd.date_request,101) BETWEEN '09/10/2013' AND
'09/11/2013'
AND ot.status ='A'
ORDER BY otd.date_request,ot.date_request ASC
expected RESULT :
userid | task | date_request | approved_by
xxx 1 09/10/2013 admin1
xxx 2 09/10/2013 admin1
xxx 5 09/11/2013 admin2
xxx 6 09/11/2013 admin2
but it give me this RESULT :
userid | task | date_request | approved_by
xxx 1 09/10/2013 admin1
xxx 2 09/10/2013 admin1
xxx 1 09/10/2013 admin2
xxx 2 09/10/2013 admin2
xxx 5 09/11/2013 admin1
xxx 6 09/11/2013 admin1
xxx 5 09/11/2013 admin2
xxx 6 09/11/2013 admin2
I also tried GROUP BY otd.task,otd.date_request,ot.approved_by but it
gives me this error:
Column 'otd.userid' is invalid in the select list because it is not
contained in either an aggregate function or the GROUP BY clause.
Thank you in advance!

No comments:

Post a Comment