简体   繁体   English

按ID分组并在SQL中找到时间的最小值和最大值

[英]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. 我在SQL中获得了第一个任务,但是对订单函数感到困惑。 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. 我需要找到唯一的用户(即customer_id的DISTINCT),显示它是否为员工,并为每个客户找到最早和最新的购买记录。 I'm totally beginner for SQL and have no idea where to start. 我完全是SQL的初学者,不知道从哪里开始。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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