2016-08-12 62 views
0

我有2代表「房間」 &「建設」獲取最大價值

我想獲得最大(roomPrice)評爲「全面大廈成交價」通過構建分組名稱。我知道應該有一個子查詢來從roomPrice中獲取值,所以max(roomprice)會起作用,但我無法做到這一點。

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

對不起,剛開始在SQL和書籍不告訴所有人。

+0

你可以附加你的表定義@Wombat嗎? – jersoft

回答

0

試試這個方法:根據您想要的輸出

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 

這一個工作正常。 希望它有助於

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 
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將一個Table的每一行與另一個Table的所有行組合在一起。如果您使用ON添加條件,則可以減少您獲得的組合。在這種情況下,兩個表上只有具有相同buildingNo的行纔會「粘」在一起。然後我們通過這個buildingNo將它們分組,並且只接受roomPriceMAX的一行或者簡單地創建SUM

+0

是的,我看到它的作品,但我忘了提及,每個建築物有3個或更多的房間,所以他們必須在每個建築物最大生成之前加在一起。對不起 – Wombat

+0

好吧,這是一個很重要的事實知道:) 讓我們看看我能做些什麼... – Marcus

+0

用'SUM'替換MAX# – Marcus

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 
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 
+0

好的建築物1有3個房間,增加了最大房間價格2700.00和那些3房間不得不被添加到每個建築物的最大值,對於不同值的2和3也是如此。我不知道我是否正確解釋。 – Wombat