Platform: SQL Server (SSMS)
I have tables tblorder and tblorderproduct. These are the relevant columns from these tables:
Tblorder: CUID (Customer ID), OrOrderID (Order ID), CuName (Customer Name), completedate (Order Date), OrCancellation (1 = Cancelled, 0 = Normal)The table is automatically sorted in ascending order by date
Tblorderproduct: OpOrderID (Order ID), OpOrderValue (Order Value)
tblorder.ororderid = tblorderprodcut.oporderid
Objectives:
Display most recent 1 million customers (CUID and Name) with all the OrderID they are reponsible for (excluding cancelled orders).
Then insert them into a temp table
#Recent1MCus
Example
CUID OrderID CUName completedate
----------------------------------------
3 201 Joe P 2017 06 02
3 202 Joe P 2017 06 25
1 203 Jason A 2017 07 21
4 204 Jason C 2017 08 31
7 205 Nick C 2017 09 03
2 206 Ari C 2017 10 01
3 207 Joe P 2017 10 21
1 208 Jason A 2017 11 05
Let's say I only want most recent 2 customers (for the sake of the example) with all their orders
So the query should return:
CUID OrderID CUName completedate
----------------------------------------
1 208 Jason A 2017 11 05
1 203 Jason A 2017 07 21
3 207 Joe P 2017 10 21
3 202 Joe P 2017 06 25
3 201 Joe P 2017 06 02
So sum it up the query should:
Distinct Top 1000000 for CUID (either Group by or Distinct)
Display all Order ID that is connected with that CUID (if group by CUID, OrOrderID, you can't put the top 1000000 limit on CUID?)
When selecting the customers, I want the most recent 1000000 distinct CUIDs, therefore the completedate in desc order.
I am just completely lost after trying different methods. I appreciate any help!
Thanks!