根据一个表中的第二个字段获取一个字段的MAX值

时间:2016-08-12 05:28:32

标签: mysql sql

我有两张桌子“房间”和“建筑物”

我正在尝试以建筑物名称分组的最大(roomPrice)AS“总建筑物价格”。我知道应该有一个子查询来从roomPrice获取值,所以max(roomprice)将起作用,但我无法做到这一点。

Table1 ( roomNo, buildingNo, roomType, roomPrice )
Table2 ( buildingNo, buldingName, buildingCity )

抱歉刚刚开始使用SQL,书籍并没有告诉所有人。

5 个答案:

答案 0 :(得分:0)

尝试这种方式:

public_html

根据您想要的输出,这个工作正常。 希望它有所帮助

答案 1 :(得分:0)

试试这个:

SELECT t2.buildingName as 'Building Name', MAX(t1.roomPrice) AS 'Total Building Price'
FROM Table2 t2
INNER JOIN Table1 t1 ON t1.buildingNo = t2.buldingNo
GROUP BY t2.buildingName

答案 2 :(得分:0)

尝试这个

SELECT tab1.buildingNo, MAX(tab1.roomPrice)
FROM tab1 JOIN tab2 ON tab1.buildingNo = tab2.buildingNo
GROUP BY  tab1.buildingNo

如果您想在整栋建筑物上求和,请使用此

SELECT tab1.buildingNo, SUM(tab1.roomPrice)
FROM tab1 JOIN tab2 ON tab1.buildingNo = tab2.buildingNo
GROUP BY  tab1.buildingNo

http://sqlfiddle.com/#!9/143c2/6

JOIN将一个表的每一行与另一个表的所有行组合在一起。如果您使用ON添加条件,则可以减少所获得的组合。在这种情况下,只有两个表上具有相同buildingNo的行将被"粘合"一起。然后我们按此buildingNo对它们进行分组,只使用MAX的{​​{1}}行,或者只创建roomPrice

答案 3 :(得分:0)

试试这个:

create table #Table2(buildingNo int, buldingName nvarchar(50), buildingCity    varchar(50))
  Insert into #Table2 values
  (1,'A','Delhi'),
  (2,'B','Delhi')


   Create Table #Table1  (roomNo int, buildingNo int, roomType  varchar(50), roomPrice int)
   Insert into #Table1 values
   (1,1,'2BHK',50000),
   (2,2,'2BHK',60000),
  (3,1,'1BHK',55000),
  (4,2,'2BHK',65000),
  (4,1,'2BHK',80000),
   (4,2,'2BHK',90000)

 SELECT max(roomPrice) AS [Total Building Price],buldingName FROM #Table1  t1
    JOIN  #Table2 t2
    ON t1.buildingNo=t2.buildingNo
    group by buldingName

答案 4 :(得分:0)

如果您只需要知道max(roomPrice):

,则不需要子查询
SELECT tab2.buildingName, max(tab1.roomPrice) AS TotalBuildingPrice
FROM tab1
JOIN tab2 ON tab1.buildingNo = tab2.buildingNo
GROUP BY tab2.buildingName

然而,由于您的问题表明总建筑价格,您实际上可能意味着max(sum()):

SELECT tab2.buildingName, sum(tab1.roomPrice) AS TotalBuildingPrice
FROM tab1
JOIN tab2 ON tab1.buildingNo = tab2.buildingNo
GROUP BY tab2.buildingName
ORDER BY TotalBuildingPrice DESC
LIMIT 1