繁体   English   中英

在一张表中基于第二个字段获取一个字段的MAX值

[英]Getting MAX value of one field based on 2nd field in one table

我有2个桌子“房间”和“建筑物”

我正在尝试按建筑物名称分组获得最大“房间总价” AS“总建筑物价”。 我知道应该有一个子查询来从roomPrice获取值,因此max(roomprice)可以工作,但我无法正确地做到这一点。

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

抱歉,SQL才刚刚开始,书还没有全部介绍。

尝试这种方式:

select a.buildingNo,b.buildingName,b.buildingCity ,a.max_room_price from
(select buildingNo,max(roomPrice) as max_room_price from table1 GROUP BY buildingNo) as a

LEFT JOIN
(select buildingNo, buildingName,buildingCity from table2)as b
on a.buildingNo = b. buildingNo

根据您想要的输出,这一项工作正常。 希望能帮助到你

也尝试一下:

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

试试这个

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它们进行分组,并仅使用具有roomPrice MAXroomPrice或简单地创建SUM

尝试这个:

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

如果只需要知道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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM