Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using datepart() with the group by command

I am beating my head against something that is, I'm sure, very obvious -

I have a bit of SQL code designed to sum the total selling price of each invoice in my store and then organize it by Month.

select SUM(totalsellingprice) from dbo.tblServiceOrders
where datepart(MONTH,dbo.tblServiceOrders.datereceived) =12

As far as I understand it, that should return the sum of all the totatlsellingprice from month 12 (December). Currently, this query returns

135998.92

However, if I then try to put that into a group by to get it to spit it out for all months, the number changes.

select SUM(totalsellingprice) from dbo.tblServiceOrders
group by datepart(MONTH,dbo.tblServiceOrders.datereceived)

And I get this table -

 1 - 110567.70
 2 - 60059.59
 3 - 135998.92
 4 - 63089.22
 5 - 102287.01
 6 - 71088.68
 7 - 149102.10
 8 - 67722.65
 9 - 67122.45
10 - 64234.82
11 - 7542.05
12 - 130461.10

There are 12 rows, which sounds good to me (12 months in a year) but the last row is 130461.

How is it possible that row 12 from the second search does not equal what I did in the first search? I feel like I'm missing something obvious but I can't for the life of me figure out what.

Any and all help will be much appreciated!

like image 987
Zac Cramer Avatar asked Dec 19 '12 16:12

Zac Cramer


1 Answers

I got it:

Your query is very confusing since it does not include the MONTH column:

If you would have done that, you would have realized your query is not ordered by MONTH and so, the MONTH 12 is returned as the 3rd row of your query.

;)

select SUM(totalsellingprice) from dbo.tblServiceOrders
group by datepart(MONTH,dbo.tblServiceOrders.datereceived)
order by datepart(MONTH,dbo.tblServiceOrders.datereceived)

And please, don't refer to the row index to choose which month is related to which sum. And should be a good idea to also discriminate the year (if you need to).

like image 100
Francis P Avatar answered Sep 20 '22 08:09

Francis P