从一对多联接中选择最大值记录

时间:2018-11-25 17:36:13

标签: sql sql-server join

我想联接两个表,但是第二个表包含多行参数,我希望通过联接来建立这些参数。

TABLE1

+------------+-----------+
|   Ddate    |    ROOMNO |
+------------+-----------+
| 2018-22-11 |       101 |
| 2018-22-11 |       102 |
| 2018-22-11 |       103 |
| 2018-22-11 |       104 |
+------------+-----------+

TABLE2 (每个房间号多行)

+------------+-----------+------------------+
|   Ddate    |    ROOMNO |  MaxVoltage      |
+------------+-----------+------------------+
| 2018-22-11 |       101 |   230            |
| 2018-22-11 |       101 |   240            |
| 2018-22-11 |       101 |   250   -----MAX |
| 2018-22-11 |       102 |   230            |
| 2018-22-11 |       102 |   255   -----MAX |
+------------+-----------+------------------+

期望结果(我希望该日期的房间的最大电压)

+------------+-----------+------------+
|   Ddate    |    ROOMNO | MaxVoltage |
+------------+-----------+------------+
| 2018-22-11 |       101 |        250 |
| 2018-22-11 |       102 |        255 |
| 2018-22-11 |       103 |        235 |
| 2018-22-11 |       104 |        238 |
| 2018-22-11 |       105 |        255 |
+------------+-----------+------------+

5 个答案:

答案 0 :(得分:1)

SELECT t2.d, t2.roomno, max(t2.maxvolt)
FROM table1 AS t1 JOIN table2 AS t2 ON t1.ddate = t2.ddate 
AND t1.roomno = t2.roomno
GROUP BY t2.d, t2.roomno;

答案 1 :(得分:0)

使用子查询

    select t1.dDate,t1.roomno,mvoltage from table1 t1 join
    (select Ddate ,roomno,max(MaxVoltage ) as mvoltage from table2
    group by Ddate,roomno
    ) t2 on t1.Ddate=t2.Ddate 

答案 2 :(得分:0)

首先,您将使用日期和房间号定期连接两个表。 然后使用over子句对电压字段使用合计函数max,然后按房间号和日期进行分组,如下所示

select distinct t1.Ddate, t1.RoomNo, MAX(t2.MaxVoltage) over(partition by t1.RoomNo order by t1.Ddate) MaxVoltage
from Table1 t1
join Table2 t2 on t2.Ddate = t1.Ddate and t2.RoomNo = t1.RoomNo

答案 3 :(得分:0)

使用apply

select t1.*, t2.maxvoltage
from table1 t1 outer apply
     (select top (1) t2.*
      from table2 t2
      where t2.roomno = t1.roomno and t2.ddate = t1.ddate
      order by maxvoltage desc
     ) t2;

答案 4 :(得分:0)

select t1.dDate,t1.roomno, mvoltage from table1 t1 join
    (select Ddate ,roomno,max(MaxVoltage ) as mvoltage from table2
    group by Ddate,roomno
    ) t2 on t1.Ddate=t2.Ddate and t1.Roomno = t2.RoomNo