这里我有一个Table1(主表(AAA))和Table2(sub_master表(BBB))。 我已经通过某种条件从AAA到BBB提取了一些数据。
(表1 AAA)
ID Date1 Grade1
1 2013-07-12 00:00:00.000 1
1 2014-04-02 00:00:00.000 1
1 2014-12-29 00:00:00.000 NULL
100000 2012-10-01 00:00:00.000 NULL
100000 2015-10-08 00:00:00.000 NULL
100000 2017-01-10 00:00:00.000 1
100000 2018-05-29 00:00:00.000 2
表2 BBB
ID Date2 Grade2
1 2013-07-12 00:00:00.000 1
1 2014-04-02 00:00:00.000 1
100000 2017-01-10 00:00:00.000 1
100000 2018-05-29 00:00:00.000 2
现在我想使用另一种条件从AAA到BBB提取另外一些数据。
选择MIN(date2),然后找到MAX(date1) 这意味着OP应该像 请帮助我解决此问题
预先感谢!100000 2015-10-08 00:00:00.000 NULL
答案 0 :(得分:1)
尝试如下
with
t1 as
(
select id,max(date1) as date1 from AAA where grade1 is null
group by id
),
t2 as
(
select id, min(date2) as date2 from BBB group by id
) select t1.*,t2.*
from t1 join t2 on t1.id=t2.id
where t1.date1<t2.date2
答案 1 :(得分:0)
从AAA中选择Max(Date1),其中Date1 < (从BBB中选择MIN(DATE2)) AND GRADE1为NULL
答案 2 :(得分:0)
您可以将英语直接翻译成sql:
SELECT TOP 1 * FROM aaa
WHERE date1 < (SELECT MIN(date2)FROM bbb) and grade1 is null
ORDER BY date1 desc
螺母和螺栓是根据您的英语要求提供的:它们获得的所有行的日期均小于表2中的最小值。具有最大日期的行是按日期降序排列的最上面1行
答案 3 :(得分:0)
SELECT *
FROM (
-- Get Max of Date1 with Grade1 is null vallue
SELECT ID, Date1 = MAX(Date1)
FROM Table1
WHERE Grade1 IS NULL
GROUP BY ID
) t1
INNER JOIN
(
-- Get Min of Date2
SELECT ID, Date2 = MIN(Date2)
FROM Table2
GROUP BY ID
) t2
ON t1.ID = t2.ID
WHERE t1.Date1 < t2.Date2
答案 4 :(得分:0)
SELECT *
FROM (
SELECT ID, MAX(Date1)
FROM Table1
WHERE Grade1 IS NULL
GROUP BY ID
) t1
INNER JOIN
(
SELECT ID, Date2 = MIN(Date2)
FROM Table2
GROUP BY ID
) t2
ON t1.ID = t2.ID
and t1.Date1 < t2.Date2