In SQL Server 2008 I have a Table- Fruits
Items Orders
Bananas 6
Bananas 2
Bananas 1
Mangos 4
Mangos 3
Apples 7
Apples 1
Apples 3
Apples 3
Using variables, how I can get below output. I am requesting variables because I would like perform several mathematical operations not described in this example.
Items Number of Orders Total Order Quantity Average Order Quantity
Bananas 3 9 3
Mangos 2 7 3.5
Apples 4 14 3.5
‘Total Order Quantity’ shows sum of all orders for given item
‘Average Order Quantity’ = ‘Total Order Quantity’/’Number of Orders’
Many thanks.
Create table Fruits (Items varchar(10), Orders int)
insert into Fruits values ('Bananas',6)
insert into Fruits values ('Bananas',2)
insert into Fruits values ('Bananas',1)
insert into Fruits values ('Mangos',4)
insert into Fruits values ('Mangos',3)
insert into Fruits values ('Apples',7)
insert into Fruits values ('Apples',1)
insert into Fruits values ('Apples',3)
insert into Fruits values ('Apples',3)
Yes, really should steer clear of cursors when possible. Something like this approach would probably be best, storing the results of the query in a temporary table, and then running update statements to get your calculations:
or if you can get all your calculations in a single row or joins with another table, you can do it in a single statement, like: