SQL Group By

The setup of my question:
data:
customer_id                   Item_ID                order_date
1                                      apples                  11/1/17
2                                      apples                   1/1/17
3                                      apples                   5/1/17

My question is I want to see what customer purchase apples last and what was the sales date

Below is my script but when I run this it show them all since I have customer_id in the group by.

SELECT DISTINCT item_id, MAX(order_date) AS last_sales_date, DATEDIFF(day, MAX(order_date), GETDATE()) AS days_since_last_sold, customer_id
FROM            p21_order_view
GROUP BY item_id, customer_id
HAVING        (item_id = 'apples')
ORDER BY last_sales_date

Below are the results I want to see:
customer_id                   Item_ID                order_date
1                                      apples                  11/1/17

Thanks
LVL 1
abarefootAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

NerdsOfTechTechnology ScientistCommented:
try:

 SELECT customer_id, item_id, MAX(order_date) AS last_sales_date, DATEDIFF(day, MAX(order_date), GETDATE()) AS days_since_last_sold
 FROM  p21_order_view
 GROUP BY item_id 
 HAVING item_id = 'apples'
 ORDER BY last_sales_date

Open in new window

0
abarefootAuthor Commented:
All you did is remove customer_id from the group by which will not work.  When you do that you get the below error

Msg 8120, Level 16, State 1, Line 2
Column 'p21_order_view.customer_id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
0
NerdsOfTechTechnology ScientistCommented:
You're right, this works:

 
 SELECT TOP 1
 customer_id, 
 item_id, 
 MAX(order_date) AS last_sales_date, 
 DATEDIFF(day, MAX(order_date), GETDATE()) AS days_since_last_sold
 FROM  p21_order_view
 GROUP BY item_id, customer_id 
 HAVING item_id = 'apples'
 ORDER BY last_sales_date DESC;

Open in new window


http://sqlfiddle.com/#!6/3132fd/23
0
CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

abarefootAuthor Commented:
HA yes that works but not what I'm looking for.   I'm needing the one with the latest order_date.  So if the second one had the latest order date and all you do it say select Top 1 it will not select the correct one.  I explained this in the original post but just encase this should clear it up.

customer_id                   Item_ID                order_date
2                                      apples                  1/1/17
1                                      apples                   11/1/17
3                                      apples                   5/1/17

The results still need to be
1                                      apples                   11/1/17
0
NerdsOfTechTechnology ScientistCommented:
I'm returning the correct results

customer_id      item_id      last_sales_date      days_since_last_sold
1      apples      2017-11-01      14

I'll even add some more values:

Proof:

http://sqlfiddle.com/#!6/6b207/1
0
Pawan KumarDatabase ExpertCommented:
Please use this tested solution-

/*------------------------

 SELECT customer_id, Item_ID, order_date FROM
 (
	 SELECT * , ROW_NUMBER() OVER (PARTITION BY Item_ID ORDER BY order_date DESC) rnk
	 FROM p21_order_view
	 WHERE Item_ID = 'apples'
)o WHERE rnk = 1 
------------------------*/
customer_id Item_ID                                            order_date
----------- -------------------------------------------------- ----------
4           apples                                             2017-11-01

(1 row(s) affected)

Open in new window

0
abarefootAuthor Commented:
OK that's great but what if I'm wanting to select more then just apples and have hundreds of items I'm wanting to select the latest order date and customer
Example:
customer_id                   Item_ID                order_date
2                                      apples                  1/1/17
4                                      orange                  4/1/17
1                                      apples                   11/1/17
3                                      apples                   5/1/17
1                                      orange                  12/1/16


results need to be
1                                      apples                   11/1/17
4                                      orange                  4/1/17
0
Pawan KumarDatabase ExpertCommented:
you can use below. Just remove the where clause,

/*------------------------

 SELECT customer_id, Item_ID, order_date FROM
 (
	 SELECT * , ROW_NUMBER() OVER (PARTITION BY Item_ID ORDER BY order_date DESC) rnk
	 FROM p21_order_view	 
)o WHERE rnk = 1 
------------------------*/
customer_id Item_ID                                            order_date
----------- -------------------------------------------------- ----------
1           apples                                             2017-11-01
6           oranges                                            2017-06-01
7           peaches                                            2017-07-01

(3 row(s) affected)

Open in new window

1

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
abarefootAuthor Commented:
Thanks for the help!  That's exactly what I was looking for.
0
NerdsOfTechTechnology ScientistCommented:
ROW_NUMBER OVER (PARTITION BY will do the trick. Thanks Pawan Kumar. Your solution is optimal.
0
Pawan KumarDatabase ExpertCommented:
welcome. glad to help as always.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
SQL

From novice to tech pro — start learning today.