x

Group By Question

I am trying to write a query to return how many items were sold in particular months. Right now its returning the same item multiple times per month.

select distinct itemID, sum(AmtSold), yrmonth
from inventory
where YrMonth between 201105 and 201108
Group by itemID, yearmonth, AmtSold
Order by yearmonth , productid

I just want each ItemID returned once per month with the Amtsold summed for the whole month per item.

Result I want:

item id  AmtSold  YrMonth
123       230     201105    
456       150     201105
123       175     201106
456       122     201106
more ▼

asked Oct 13, 2011 at 08:09 PM in Default

sqlnewb gravatar image

sqlnewb
216 27 30 31

(comments are locked)
10|1200 characters needed characters left

1 answer: sort voted first
Just remove AmtSold from the group by list
 select distinct itemID, sum(AmtSold), yrmonth from inventory where YrMonth between 201105 and 201108 Group by itemID, yearmonth, Order by yearmonth , productid 
more ▼

answered Oct 13, 2011 at 08:46 PM

Cyborg gravatar image

Cyborg
10.6k 36 40 45

You probably mean "remove AmtSold".
Oct 14, 2011 at 12:06 AM Håkan Winther
Thanks Hakan!
Oct 14, 2011 at 12:16 AM Cyborg
(comments are locked)
10|1200 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

New code box

There's a new way to format code on the site - the red speech bubble logo will automatically format T-SQL for you. The original code box is still there for XML, etc. More details here.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

SQL Server Central

Need long-form SQL discussion? SQLserverCentral.com is the place.

Topics:

x1834
x36

asked: Oct 13, 2011 at 08:09 PM

Seen: 731 times

Last Updated: Oct 13, 2011 at 08:09 PM