Sunday, February 26, 2012

group by clause

Hi all,
i have 2 tables in pubs database, first one is titles and second
one is sales,
i want to get sum of quantity which is in sales table along with title_id
and title.
i'm executing this query
select titles.title_id,title,sum(qty) as quantity from titles join sales on
sales.title_id=titles.title_id group by titles.title_id
This is giving some error,I'm not able to find, where this error comingWhat error?
Anyway, look up GROUP BY in Books Online. You're selecting two columns (not
counting the aggregate), but only grouping by one.
ML
http://milambda.blogspot.com/|||Manish ML is right...
SELECT
titles.title_id
,title
,SUM(qty) as quantity
FROM
titles join sales on
sales.title_id=titles.title_id
GROUP BY titles.title_id
is what you had!
you just need to add the title column to the GROUP BY like so
SELECT
titles.title_id
,title
,SUM(qty) as quantity
FROM
titles join sales on
sales.title_id=titles.title_id
GROUP BY titles.title_id, titles.title
The reason: if a column is not in an aggregate function in the SELECT list
of a GROUP BY query, it must be included in the GROUP BY clause, therefore
you don't have to put SUM(qty) (since it's in an aggregate function) in the
GROUP BY, and in fact can't.
Regards
CharlesA

No comments:

Post a Comment