SQL - 日期在where子句中获取最早的日期

时间:2016-05-03 08:14:40

标签: sql postgresql

假设我有这个数据

userid  logdate      event
0       2009-01-01   x
1       2010-01-01   x
1       2011-01-01   xy
1       2011-01-05   xz
2       2011-01-21   xx
2       2011-01-22   xx

我需要让在2011-01-01和2011-02-01之间进行日志记录的用户 包括自开始以来的第一个日志。

预期结果

userid  first_logdate      
1       2010-01-01  
2       2011-01-21

当前解决方案

   SELECT user_id, first_logdate
   FROM (
     SELECT user_id, logdate, MIN(logdate) AS first_logdate
     FROM tablex
     GROUP BY 1
   )
   WHERE logdate BETWEEN '2011-01-01' AND '2011-02-01'

如果数据很大,此查询是否已优化?

3 个答案:

答案 0 :(得分:0)

使用Group ByMin汇总

SELECT DISTINCT userid,
                (SELECT Min(first_logdate)
                 FROM   yourtable B
                 WHERE  a.userid = b.userid)
FROM   yourtable A
WHERE  first_logdate BETWEEN '2011-01-01' AND '2011-02-01' 

答案 1 :(得分:0)

GROUP BY用户ID并将MIN日期作为其首次登录日期

SELECT userid, MIN(logdate) AS first_logdate
FROM table
WHERE logdate BETWEEN '2011-01-01' AND '2011-01-21'
GROUP BY userid

答案 2 :(得分:0)

尝试:

SELECT userid, MIN(t1.logdate) AS first_logdate
FROM table t1
JOIN table t2 USING ( userid )
WHERE t2.logdate BETWEEN '2011-01-01' AND '2011-01-21'
GROUP BY userid

也可以使用自联接:

EXISTS

以及使用SELECT userid, MIN(logdate) AS first_logdate FROM table t1 WHERE EXISTS ( SELECT 555821 FROM table t2 WHERE t2.logdate BETWEEN '2011-01-01' AND '2011-01-21' AND t1.userid = t2.userid ) GROUP BY userid 运算符

的第三个版本
SELECT  left_id
FROM    `test`
WHERE   right_id IN (90,91,93,94,95)
GROUP BY left_id
HAVING  COUNT(DISTINCT right_id) = 5
UNION 
SELECT  left_id
FROM    `test`
WHERE   right_id IN (90,92,93,94,95)
GROUP BY left_id
HAVING   COUNT(DISTINCT right_id) = 5