我非常感谢为此编写选择查询的所有帮助。
MyTable
sw_id | url_id | open_date | valid
----------------------------------------
101 | com | 2013-01-01 | 1
202 | net | 2013-01-02 | 1
202 | net | 2013-02-02 | 1
303 | com | 2013-01-03 | 1
303 | com | 2013-02-03 | 1
303 | com | 2013-03-03 | 1
404 | org | 2013-01-04 | 1
404 | org | 2013-02-04 | 1
404 | gov | 2013-02-04 | 1
404 | gov | 2013-04-04 | 1
...
我们需要找到有效的(有效= 1)行,其中相同的sw_id,url_id得到的open_date更少。
选择查询应该输出上面的行:
查询输出
sw_id | url_id | open_date | valid | min_open_d
-----------------------------------------------------
202 | net | 2013-02-02 | 1 | 2013-01-02
303 | com | 2013-02-03 | 1 | 2013-01-03
303 | com | 2013-03-03 | 1 | 2013-01-03
404 | org | 2013-02-04 | 1 | 2013-01-04
404 | gov | 2013-04-04 | 1 | 2013-02-04
如您所见,我们只选择open_date高于最低值min(open_date)的行。
我希望你从上面的描述中理解这个问题。
答案 0 :(得分:1)
如果你在这里展示自己的努力会很好,但基本上子查询是最容易理解的方法之一。
SELECT
sw_id,
url_id,
open_date,
valid,
(
SELECT MIN(open_date)
FROM MyTable t2
WHERE t2.sw_id = t1.sw_id GROUP BY t2.sw_id
) AS min_open_d
FROM
MyTable t1
WHERE
valid = 1
ORDER BY
open_date DESC
答案 1 :(得分:1)
你的样本和解释对解释有点开放,但这样的事情应该很接近。
SELECT sw_id ,
url_id ,
open_date ,
valid ,
( SELECT MIN(open_date)
FROM mytable mt2
WHERE mt2.sw_id = mt1.sw_id
AND mt1.url_id = mt2.url_id
GROUP BY mt2.sw_id, mt2.url_id
) AS min_open_d
FROM mytable mt1
WHERE valid = 1 AND mt1.open_date >
( SELECT MIN(open_date)
FROM mytable mt3
WHERE mt3.sw_id = mt1.sw_id
AND mt1.url_id = mt3.url_id
GROUP BY mt3.sw_id, mt3.url_id
)
答案 2 :(得分:0)
使用OLAP函数可以更好地解决这个问题:
select * from (
select sw_id,
url_id,
open_date,
valid,
min(open_date) over (partition by sw_id,url_id) as min_open_d
from MyTable
where valid = 1
)
where open_date <> min_open_d;
这也应该比子查询更有效。