在一列上显示最大值但从多个表中显示多个

时间:2015-02-24 19:06:47

标签: sql sql-server-2008

如何编写查询以输出第1列中每个相应记录的max 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

RAW OUTPUT

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

3 个答案:

答案 0 :(得分:2)

column1上将table1连接到自身以获取所有兄弟行,然后左连接到table2:

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

请参阅SQLFiddle

答案 1 :(得分:1)

您可以尝试使用聚合函数MAX()作为窗口函数:

SELECT column1, column2, MAX(column3) OVER ( PARTITION BY column1 ) AS MAXcolumn3
  FROM table1;

我不知道你桌子的精确架构所以我不知道上面是否会返回重复。

如果您有两个表,那么您可以使用原始查询并使用子查询或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;

答案 2 :(得分:0)

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;