michaeleaton 36224 (8/27/2014)
Thanks everyone for your help. Jack's solution works just great. I probably should have posted the output I wanted, but in essence I wanted it grouped by Username with the count of orders for that user, I've tried to modify Jack's solution to do this but having no luck at the moment..
So I think this might be want to you want:
WITH newCustomers
AS (
SELECT
*,
COUNT(*) OVER (PARTITION BY CustomerID) AS orderCount
FROM
dbo.Orders AS O
WHERE
/* since PaymentDate is defined as DateTime using this is more consistent
method then between because with between you'd need to include the time
portion to be sure you get the full day for most recent date */
O.PaymentDate >= '2014-07-29' AND
O.PaymentDate < '2014-08-27'
)
SELECT
COUNT(*) AS orderCountByUser,
NC.UserID,
U.UserName
FROM
newCustomers AS NC
JOIN dbo.aspnet_Users AS U
ON NC.UserID = U.UserID
WHERE
/* the NOT EXISTS enforces that they have not had an order outside the
date range as well. I'm doing this because I interpreted this,
"but also taking into account if they have ever had a paid order outside of that date range",
to mean that you didn't want customers who had an order outside the date range. */
NOT EXISTS ( SELECT
1
FROM
Orders AS O
WHERE
NC.CustomerID = O.CustomerID AND
(
O.PaymentDate < '2014-07-29' OR
O.PaymentDate >= '2014-08-27'
) ) AND
NC.orderCount = 1
GROUP BY
NC.UserID,
U.UserName;
Jack Corbett
Consultant - Straight Path Solutions
Check out these links on how to get faster and more accurate answers:
Forum Etiquette: How to post data/code on a forum to get the best help
Need an Answer? Actually, No ... You Need a Question