简体   繁体   中英

SELECT Records from the last time a record was recorded using SQL

I have this table where I enter sales by customer name and date

So I have two fields where I select the customer name and Date, Then I make a sales.

Everything is fine until I tried to add a feature when you select the customer name. I want the last time he or she made a sale to show the total amount of the sale.

Already the total amount is recorded at the time of entry and stored in another column in the table.

Now my problem is with the date. Let's just say the last time, that particular customer made a sale was on the 20th March. And he or she is now making a sale on the 24th March which is today.

I want to query out the sales amount he or she made on the 20th March. As I already said, I have the total sales amount stored in the table already so I could just use

SELECT CustomerName, totalAmount 
FROM transactions 
WHERE DATE(created_at) = DATE(NOW() - INTERVAL 1 DAY);

But with this method, it's referring me to 24th march which is not what I want. Can someone guide me on how to accomplish this?

As the query will have to find the last date the customer made the sale and bring forward the total sales amount.

Thank you all.

您可以通过简单的限制和排序来做到这一点

   SELECT CustomerName, totalAmount FROM transactions WHERE CustomerName = $CustomerName order by created_at desc limit 1,1

You can make use of subquery

  SELECT CustomerName, totalAmount 
  (select  top 1 DATE(created_at)  FROM transactions a where 
   a.CustomerName= b.CustomerName) lastSaleDate
  FROM transactions b
  where  CustomerName= $customer 

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