php - Most efficient way of getting first payment method used by all users -
lets have table in mssql database called "customers". have table called "orders", each of contains "customerid". want do, generate summary of payment method (let's call "paymentmethod") used first "order" of every "customer".
the method have been using conduct customer selection query...
select <columns> customers <where>
...and each result, conduct separate query obtain customer's first order's payment method:
select top 1 paymentmethod orders order timestamp asc
this process has benefit of obtaining data want in simple way that's easy modify, huge disadvantage of meaning query carried out every customer, mean tens-of-thousands of queries every single time!
is there more efficient way of doing i'm not thinking of? i'm racking brain think of way of selecting directly "orders" table begin with, requirement query not group "customerid" fetch min() of "timestamp" , return "paymentmethod" of min() record doesn't seem work?
you can use row_number
this:
select paymentmethod ( select paymentmethod, row_number() on (partition customerid order timestamp asc) rn orders ) t t.rn = 1
the above query picks earliest-per-group record.
Comments
Post a Comment