字段少于 select 的分组依据
Group By with fewer fields than the select
我有两个 Oracle 表:
USER(ID*,NAME,SURNAME)
MATCH(ID*,START_DATE,END_DATE,MATCH_CODE,ID_USER**)
我需要一个查询来为每个 USER 获取 END_DATE 和 START_DATE 以及 NAME 和 MATCH_CODE 字段之间以秒为单位的最大差异的匹配项。
我的查询:
SELECT A.ID,A.NAME,MAX(extract(second from (END_DATE-START_DATE))
+ extract(minute from (END_DATE-START_DATE)*60
+ extract(hour from (END_DATE-START_DATE)*60*60
+ extract(day from (END_DATE-START_DATE)*60*60*24) max_differance
FROM USER A JOIN MATCH B
ON A.ID = B.ID_USER
GROUP BY A.ID;
我正在考虑这个查询,但显然它给出了一个错误,因为在 GROUP BY 中 select 的所有字段都去。另外我需要 MATCH_CODE 字段,我该怎么办?
聚合 name
列并使用 MAX ... KEEP
得到 match_code
:
SELECT u.id,
MAX(u.name) AS name,
MAX(end_date - start_date)*24*60*60 AS max_difference,
MAX(match_code) KEEP (
DENSE_RANK LAST
ORDER BY end_date - start_date NULLS FIRST
) As match_code
FROM "USER" u
INNER JOIN match m
ON (u.id = m.id_user)
GROUP BY u.id
或者,使用解析函数:
SELECT id,
name,
max_difference,
match_code
FROM (
SELECT u.id,
u.name,
(end_date - start_date)*24*60*60 AS max_difference,
match_code,
ROW_NUMBER() OVER (PARTITION BY u.id ORDER BY end_date - start_date DESC)
AS rn
FROM "USER" u
INNER JOIN match m
ON (u.id = m.id_user)
)
WHERE rn = 1;
我有两个 Oracle 表:
USER(ID*,NAME,SURNAME)
MATCH(ID*,START_DATE,END_DATE,MATCH_CODE,ID_USER**)
我需要一个查询来为每个 USER 获取 END_DATE 和 START_DATE 以及 NAME 和 MATCH_CODE 字段之间以秒为单位的最大差异的匹配项。
我的查询:
SELECT A.ID,A.NAME,MAX(extract(second from (END_DATE-START_DATE))
+ extract(minute from (END_DATE-START_DATE)*60
+ extract(hour from (END_DATE-START_DATE)*60*60
+ extract(day from (END_DATE-START_DATE)*60*60*24) max_differance
FROM USER A JOIN MATCH B
ON A.ID = B.ID_USER
GROUP BY A.ID;
我正在考虑这个查询,但显然它给出了一个错误,因为在 GROUP BY 中 select 的所有字段都去。另外我需要 MATCH_CODE 字段,我该怎么办?
聚合 name
列并使用 MAX ... KEEP
得到 match_code
:
SELECT u.id,
MAX(u.name) AS name,
MAX(end_date - start_date)*24*60*60 AS max_difference,
MAX(match_code) KEEP (
DENSE_RANK LAST
ORDER BY end_date - start_date NULLS FIRST
) As match_code
FROM "USER" u
INNER JOIN match m
ON (u.id = m.id_user)
GROUP BY u.id
或者,使用解析函数:
SELECT id,
name,
max_difference,
match_code
FROM (
SELECT u.id,
u.name,
(end_date - start_date)*24*60*60 AS max_difference,
match_code,
ROW_NUMBER() OVER (PARTITION BY u.id ORDER BY end_date - start_date DESC)
AS rn
FROM "USER" u
INNER JOIN match m
ON (u.id = m.id_user)
)
WHERE rn = 1;