Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 average?

Author  Topic 

msugradus
Starting Member

40 Posts

Posted - 2007-06-19 : 16:23:50
I am getting the number of transactions for two different months based on dates entered from the user. I need to display the number of transactions along with the average sale. I have figured out how to get the dates and sum the transactions but I can't seem to add in the average....

(@prevMonthStart datetime, @prevMonthEnd datetime, @thisMonthStart datetime, @thisMonthEnd datetime)

as

select sum(case when orders.orderdate between @prevMonthStart and @prevMonthEnd then 1 else 0 end ) as PrevMonthCount,

sum(case when orders.orderdate between @thisMonthStart and @thisMonthEnd then 1 else 0 end ) as ThisMonthCount

(how do I add in the average for both months? The column is orders.ordertotal)

NeilG
Aged Yak Warrior

530 Posts

Posted - 2007-06-19 : 16:29:44
If you are just meaning that you are wanting an average for the order.ordertotal column use the

avg(order.ordertotal)
Go to Top of Page

msugradus
Starting Member

40 Posts

Posted - 2007-06-19 : 16:49:55
I know what the avg(order.ordertotal) function is, what I am asking is how to incorporate it into the select statement so that it only adds to the total when the date matches for each month.
Go to Top of Page

Michael Valentine Jones
Yak DBA Kernel (pronounced Colonel)

7020 Posts

Posted - 2007-06-19 : 17:41:49
Group at the month level and then crosstab the grouped results:

select
PREV_MONTH_COUNT =
sum(case when PRIOR_MONTH_INDICATOR = 1 then MONTH_COUNT else 0 end),
PREV_MONTH_AVG_ORDER_TOTAL =
sum(case when PRIOR_MONTH_INDICATOR = 1 then MONTH_AVG_ORDER_TOTAL else 0 end),
CURR_MONTH_COUNT =
sum(case when PRIOR_MONTH_INDICATOR <> 1 then MONTH_COUNT else 0 end),
CURR_MONTH_AVG_ORDER_TOTAL =
sum(case when PRIOR_MONTH_INDICATOR <> 1 then MONTH_AVG_ORDER_TOTAL else 0 end)
from
(
select
[START_OF_MONTH] =
dateadd(mm,datediff(MM,0,orders.orderdate),0),
PRIOR_MONTH_INDICATOR =
max(
case
when -- First day of month for order
dateadd(mm,datediff(MM,0,orders.orderdate),0) =
-- First day of last month
dateadd(mm,datediff(MM,0,getdate())-1,0)
then 1
else 0 end),
MONTH_COUNT = count(*),
MONTH_AVG_ORDER_TOTAL = avg(orders.ordertotal)
from
orders
where
-- Select orders for current and prior month
orders.orderdate >= dateadd(mm,datediff(MM,0,getdate())-1,0)
group by
-- Start of Month
dateadd(mm,datediff(MM,0,orders.orderdate),0)
) a



CODO ERGO SUM
Go to Top of Page
   

- Advertisement -