[英]Most efficient way of getting first payment method used by all users
Lets say I have a table in a MSSQL database called "Customers". 可以说我在MSSQL数据库中有一个名为“客户”的表。 I also have a table called "Orders", each of which contains a "CustomerID".
我还有一个名为“ Orders”的表,每个表都包含一个“ 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".
我想做的是生成每个“客户”的第一个“订单”所使用的付款方式(我们称其为“ PaymentMethod”)的摘要。
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?
我正在绞尽脑汁想一种直接从“ Orders”表开始选择的方法,但是查询不仅需要按“ CustomerID”分组,还需要获取“ Timestamp”的MIN(),然后返回MIN()记录的“ PaymentMethod”似乎不起作用?
You can use ROW_NUMBER
for this: 您可以为此使用
ROW_NUMBER
:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.