SQL获取与FIRST日期条件匹配的记录

时间:2013-06-29 19:33:17

标签: sql sql-server sql-server-2008 date

我有以下

user_id job_id job_offer_date 
------- ------ --------------
1          123     2013-05-10 
1          124     2013-07-19
2          127     2013-05-10
3          128     2013-06-15 

我想在此处编写两个单独的查询以在报告中使用:

QUERY#1(我已经开始工作了)

此查询希望返回其所有FIRST职位要约日期为2013-5-10的用户。这是一个简单的查询,因为如果用户在该日期之前有任何作业,它将返回他。在这种情况下,我会看到用户#1,#2。

此查询如下所示:

SELECT DISTINCT j.* FROM job WHERE j.job_offer_date <= '2013-05-10'

QUERY#2(这是我真正的问题)

如何退回第一份工作邀请日期为2013-5-10之后和2013-7-19之前的用户。在这种情况下,由于用户#1在2013-5-10之前有他的第一个优惠,他不应该被包括在结果中。此结果集应仅包含用户#3。

这里最重要的关键是因为用户#1在2013-5-10之前有他的第一个优惠,他应该从查询#2的结果集排除

5 个答案:

答案 0 :(得分:1)

相关的第一份工作机会。

select user_id, min(job_offer_date) as first_offer
from job
group by user_id
having min(job_offer_date) > '2013-05-10'
   and min(job_offer_date) < '2013-07-19'

加入该套装以获取用户。我猜测用户数据存储在用户表中。

select u.*
from users u
inner join (select user_id, min(job_offer_date) as first_offer
            from job
            group by user_id
            having min(job_offer_date) > '2013-05-10'
               and min(job_offer_date) < '2013-07-19') o
        on o.user_id = u.user_id;

答案 1 :(得分:0)

如果我记得我的SQL日期正确,那么它看起来不会是这样的:

SELECT DISTINCT j.* FROM job WHERE j.job_offer_date > '2013-05-10' AND j.job_offer_data < '2013-7-19'
编辑:我误解了你的问题。以上将查找在列出的两个日期之间(但不在其上)的任何用户。 Oleh Nechytailo有更好的答案。

答案 2 :(得分:0)

select user_id, job_id, job_offer_date
from 
    (select user_id
        , job_id
        , job_offer_date
        , row_number() over 
                (partition by user_id order by job_offer_date) rown 
     from job) sub
where sub.rown = 1 and sub.job_offer_date > '2013-05-10' and sub.job_offer_date < '2013-07-19'

答案 3 :(得分:0)

一定会有效

WITH TEMP 
AS
(
SELECT *
FROM Job AS J
)

SELECT *
FROM TEMP AS A
WHERE OFFERdATE > '2013-05-10' AND oFFERdATE < '2013-7-19' AND
1 = CASE WHEN (SELECT COUNT(*) FROM TEMP WHERE OFFERdATE <= '2013-05-10' AND USERID = A.USERID) > 0 THEN      0 ELSE 1 END

答案 4 :(得分:0)

--------------
-- sample data
--------------
declare @data table
(
    user_id int,
    job_id int,
    job_offer_date datetime
)

insert into @data (user_id, job_id, job_offer_date) values 
    (1, 123, '2013-05-10'),
    (1, 124, '2013-07-19'),
    (2, 127, '2013-05-10'),
    (3, 128, '2013-06-15')

-----------
-- solution
-----------
select user_id from @data
group by user_id
having min(job_offer_date) > '2013-05-10' and min(job_offer_date) < '2013-07-19'