简体   繁体   中英

Most efficient way of getting first payment method used by all users

Lets say I have a table in a MSSQL database called "Customers". I also have a table called "Orders", each of which contains a "CustomerID". What I want to do, is to generate a summary of what payment method (let's call that "PaymentMethod") was used for the first "Order" of every "Customer".

The method I have been using for this is to conduct my customer selection query...

SELECT <Columns> FROM Customers <WHERE>

...and then for each result, conduct a separate query to obtain the customer's first order's payment method:

SELECT TOP 1 PaymentMethod FROM Orders ORDER BY Timestamp ASC

This process has the benefit of obtaining the data I want in a very simple way that's easy to modify, but the huge disadvantage of meaning a query is carried out for every customer, which could mean tens-of-thousands of extra queries every single time!

Is there a more efficient way of doing this that I'm not thinking of? I'm racking my brain to think of a way of selecting directly from the "Orders" table to begin with, but the requirement for the query to not only group by "CustomerID" but also fetch the MIN() of "Timestamp" and then return "PaymentMethod" of the MIN() record doesn't seem to work?

You can use ROW_NUMBER for this:

SELECT PaymentMethod 
FROM (
   SELECT PaymentMethod,
          ROW_NUMBER() OVER (PARTITION BY CustomerID  
                             ORDER BY Timestamp ASC) AS rn
   FROM Orders ) AS t
WHERE t.rn = 1

The above query picks the earliest-per-group record.

I guess this helps you.

SELECT C.* , O.PAYMENTMETHOD FROM Customers C
INNER JOIN Orders O ON O.CustomerID = C.CustomerID
WHERE O.OrderTime = 
(SELECT TOP 1 OrderTime FROM Customers WHERE CustomerID = C.CustomerID) -- selects customer first order based on min time

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM