简体   繁体   中英

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!

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).

Run this and see what it does...

 select dateadd(month, datediff(month, 0, datereceived),  0),
      Sum(totalsellingprice) 
 from dbo.tblServiceOrders
 group by dateadd(month, datediff(month, 0, datereceived),  0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM