简体   繁体   中英

Group by ID and find min and max of time in SQL

I got my first task in SQL, but got confused by order function. Here is an example of the table:

customer_id  is_employee     purchase_datetime
  42525           0      2007-02-19 12:49:34:560000
  42525           0      2007-02-22 16:14:55:220000
  42525           0      2007-03-02 10:56:15:200000
  52525           1      2007-02-22 14:45:18:130000
  46233           0      2007-02-21 10:29:39:010000
  53364           0      2007-02-13 08:33:34:320000
  53364           0      2007-02-20 10:01:09:540000

I need to find unique users, that would be DISTINCT of customer_id, show if it's employee or not and find earliest and latest purchase for every customer. I'm totally beginner for SQL and have no idea where to start.

probably:

select customer_id,  is_employee, max(purchase_datetime),min(purchase_datetime)
from table_name
group by customer_id,  is_employee
;

It was assumed that you cant be both employee and not one same time

  SELECT 
    customer_id
    ,is_employee
    ,MIN(purchase_datetime) AS 'EarliestPurchase'
    ,MAX(purchase_datetime) AS 'LatestPurchase' 
  FROM tbl 
  GROUP BY customer_id, is_employee

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