在一列上显示最大值,但在多个表中显示多个
display max on one column but display multiple from multiple tables
我将如何编写查询以输出第 1 列中每个对应记录的最大 column3 记录:
SELECT t1.column1, t1.column2, MAX(t2.column3) as MAXcolumn3
FROM table1 t1
LEFT JOIN table1 t2
ON t1.column2 = t2.column2
Group by t1.column1, t1.column2
原始输出
column1 column2 column3
a aa 33
a ab 02
a ac NULL
b ba 11
b bb 00
c ca NULL
c cb 00
d da NULL
期望的输出
column1 column2 column3
a aa 33
a ab 33
a ac 33
b ba 11
b bb 11
c ca 00
c cb 00
d da NULL
select tt.*
from (select t1.*,
row_number() over (partition by t1.column1 , t2.column2
order by t1.column1 desc) as column3
from table t1
LEFT JOIN table1 t2
ON t1.column2 = t2.column2
Group by t1.column1, t1.column2
) tt
where tt.column3 = 1;
在 column1
上将表 1 连接到自身以获取所有兄弟行,然后 左连接到表 2:
SELECT t1.column1, t1.column2, MAX(t3.column3) as MAXcolumn3
FROM table1 t1
JOIN table1 t2 ON t2.column1 = t1.column1
LEFT JOIN table2 t3 ON t3.column2 = t2.column2
GROUP BY t1.column1, t1.column2
您可以尝试将聚合函数 MAX()
用作 window 函数:
SELECT column1, column2, MAX(column3) OVER ( PARTITION BY column1 ) AS MAXcolumn3
FROM table1;
我不知道您 table 的精确架构,所以我不知道上面是否会 return 重复。
如果您有两个 table,那么您可以采用原始查询并使用子查询或 CTE 执行类似的操作:
WITH cte AS (
SELECT t1.column1, t1.column2, MAX(t2.column3) as MAXcolumn3
FROM table1 t1 LEFT JOIN table2 t2 -- supposed to be table1?
ON t1.column2 = t2.column2
GROUP BY t1.column1, t1.column2
)
SELECT column1, column2, MAX(MAXcolumn3) OVER ( PARTITION BY column1 ) AS MAXcolumn3
FROM cte;
我将如何编写查询以输出第 1 列中每个对应记录的最大 column3 记录:
SELECT t1.column1, t1.column2, MAX(t2.column3) as MAXcolumn3
FROM table1 t1
LEFT JOIN table1 t2
ON t1.column2 = t2.column2
Group by t1.column1, t1.column2
原始输出
column1 column2 column3
a aa 33
a ab 02
a ac NULL
b ba 11
b bb 00
c ca NULL
c cb 00
d da NULL
期望的输出
column1 column2 column3
a aa 33
a ab 33
a ac 33
b ba 11
b bb 11
c ca 00
c cb 00
d da NULL
select tt.*
from (select t1.*,
row_number() over (partition by t1.column1 , t2.column2
order by t1.column1 desc) as column3
from table t1
LEFT JOIN table1 t2
ON t1.column2 = t2.column2
Group by t1.column1, t1.column2
) tt
where tt.column3 = 1;
在 column1
上将表 1 连接到自身以获取所有兄弟行,然后 左连接到表 2:
SELECT t1.column1, t1.column2, MAX(t3.column3) as MAXcolumn3
FROM table1 t1
JOIN table1 t2 ON t2.column1 = t1.column1
LEFT JOIN table2 t3 ON t3.column2 = t2.column2
GROUP BY t1.column1, t1.column2
您可以尝试将聚合函数 MAX()
用作 window 函数:
SELECT column1, column2, MAX(column3) OVER ( PARTITION BY column1 ) AS MAXcolumn3
FROM table1;
我不知道您 table 的精确架构,所以我不知道上面是否会 return 重复。
如果您有两个 table,那么您可以采用原始查询并使用子查询或 CTE 执行类似的操作:
WITH cte AS (
SELECT t1.column1, t1.column2, MAX(t2.column3) as MAXcolumn3
FROM table1 t1 LEFT JOIN table2 t2 -- supposed to be table1?
ON t1.column2 = t2.column2
GROUP BY t1.column1, t1.column2
)
SELECT column1, column2, MAX(MAXcolumn3) OVER ( PARTITION BY column1 ) AS MAXcolumn3
FROM cte;