我有以下表格:
account
+------------+--------------+ | account_id | account_name | +------------+--------------+ | 452 | a | | 785 | b | | 985 | c | +------------+--------------+
和
task
+---------+------------+------------+ | task_id | task_date | account_id | +---------+------------+------------+ | 2 | 01-01-2013 | 452 | | 1 | 14-02-2013 | 452 | | 5 | 03-01-2013 | 452 | | 1 | 02-02-2013 | 785 | | 7 | 07-01-2013 | 785 | | 5 | 01-03-2013 | 785 | | 1 | 25-03-2013 | 985 | | 4 | 22-03-2013 | 985 | +---------+------------+------------+
我需要显示表task
和account
中的记录,以便只显示最旧的任务并且不显示日期。结果将是:
+--------------+---------+ | account_name | task_id | +--------------+---------+ | a | 2 | | b | 7 | | c | 4 | +--------------+---------+
我想到了使用min
功能。但由于我不想显示日期,我该如何使用该功能。
SELECT A.ACCOUNT_NAME,
T.TASK_ID,
MIN(T.TASK_DATE)
FROM ACCOUNT A
INNER JOIN TASK T
ON A.ACCOUNT_ID = T.ACCOUNT_ID
GROUP BY ACCOUNT_NAME, TASK_ID
答案 0 :(得分:3)
另一种方法,有点短:
select max(a.accountname) as account_name
, max(t.taskid) keep(dense_rank first
order by t.taskdate) as task_id
from account1 a
join task t
on (a.accountid = t.accountid)
group by a.accountid
结果:
ACCOUNT_NAME TASK_ID
------------ ----------
a 2
b 7
c 4
答案 1 :(得分:1)
您只需使用子查询:
SELECT S.ACCOUNT_NAME, S.TASK_ID FROM (
SELECT A.ACCOUNT_NAME, T.TASK_ID, MIN(T.TASK_DATE)
FROM ACCOUNT A
INNER JOIN TASK T
ON A.ACCOUNT_ID = T.ACCOUNT_ID
GROUP BY ACCOUNT_NAME, TASK_ID
) S
答案 2 :(得分:1)
也许是这样的:
WITH CTE
AS
(
SELECT
A.ACCOUNT_NAME,
T.TASK_ID,
ROW_NUMBER() OVER(PARTITION BY T.TASK_ID
ORDER BY T.TASK_DATE DESC) AS RowNbr
FROM ACCOUNT A
INNER JOIN TASK T
ON A.ACCOUNT_ID = T.ACCOUNT_ID
)
SELECT
CTE.ACCOUNT_NAME,
CTE.TASK_ID
FROM
CTE
WHERE
CTE.RowNbr=1;
答案 3 :(得分:1)
您可以使用分析:
SELECT account_name, task_id
FROM (SELECT a.account_name,
t.task_id,
row_number()
over(PARTITION BY a.account_id ORDER BY t.task_date) task_num
FROM account a
INNER JOIN task t ON a.account_id = t.account_id
GROUP BY account_name, task_id)
WHERE task_num = 1
或自我加入:
SELECT a.account_name, t.task_id
FROM account a
INNER JOIN task t ON a.account_id = t.account_id
WHERE (t.account_id, t.task_date) = (SELECT t_in.account_id,
MIN(t_in.task_date)
FROM task t_in
GROUP BY t_in.account_id)
答案 4 :(得分:1)
您可以使用这种简单的方法:
SELECT a.account_name, t.task_id
FROM account a,
task t
WHERE a.account_id= t.account_id
AND t.task_date in (SELECT MIN(t.task_date))
GROUP BY account_name, task_id;
答案 5 :(得分:0)
它比看起来更容易:在正常连接表之后,只需按max(tak_date)进行过滤,即可通过简单的子选择进行计算。
SELECT acc.account_name, tsk.task_id
FROM account acc
JOIN task tsk on (acc.account_id = tsk.account_id)
WHERE tsk.task_date = (
SELECT MAX(aux.task_date)
FROM task aux
WHERE aux.account_id = tsk.account_id
)