簡體   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