SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Finding out total number of orders
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

deanglen
Yak Posting Veteran

64 Posts

Posted - 01/15/2013 :  04:26:21  Show Profile  Reply with Quote
Hi

I have this script that finds extracts a full table, row by row, of each order from our e-commerce site. Do you know how I can change this so it gives a number of orders per customer?

For example

Customer ID Customer Name Number of Orders

Here is the current code

select distinct o.OrderDate, p.SKU, c.CustomerID, c.Email, c.FirstName, c.LastName from customer c
join dbo.Orders_ShoppingCart os with (NOLOCK) on os.CustomerID = c.CustomerID
join dbo.Product p with (NOLOCK) on p.ProductID = os.ProductID
join dbo.Orders o with (NOLOCK) on o.OrderNumber = os.OrderNumber
and c.IsRegistered = 1
and p.SKU like '%'
order by o.OrderDate, p.SKU, c.CustomerID

RickD
Slow But Sure Yak Herding Master

United Kingdom
3608 Posts

Posted - 01/15/2013 :  05:03:54  Show Profile  Reply with Quote
Something like this:

select c.CustomerID, c.FirstName + ' ' + c.LastName AS CustomerName, count(o.OrderNumber) As NoOrders
from customer c
join dbo.Orders_ShoppingCart os with (NOLOCK) on os.CustomerID = c.CustomerID
join dbo.Product p with (NOLOCK) on p.ProductID = os.ProductID
join dbo.Orders o with (NOLOCK) on o.OrderNumber = os.OrderNumber
and c.IsRegistered = 1
and p.SKU like '%'
GROUP BY c.CustomerID, c.FirstName + ' ' + c.LastName
order by c.CustomerID
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

India
52309 Posts

Posted - 01/15/2013 :  05:52:53  Show Profile  Reply with Quote
I prefer p.SKU > = '' over the currently written condition p.SKU like '%' so as to take advantage of an available index if present on SKU field

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

deanglen
Yak Posting Veteran

64 Posts

Posted - 01/15/2013 :  06:36:08  Show Profile  Reply with Quote
Thanks! Worked great!
Go to Top of Page

RickD
Slow But Sure Yak Herding Master

United Kingdom
3608 Posts

Posted - 01/15/2013 :  08:06:13  Show Profile  Reply with Quote
I agree with visakh16, I just didn't look..
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.05 seconds. Powered By: Snitz Forums 2000