2011-03-28 59 views
2

我如何更改SQL來給我distinct房間類型?我只想要一個roomtype_id到每個room_id。如果那有意義的話?基本上,如果有3個不同類型的5個房間,只有3個記錄應該回來。獨特的房間類型

繼承人的電流SQL的一個例子...

SELECT dbo.rooms.room_id,dbo.roomtypes.name, dbo.rooms.roomtype_id 
FROM dbo.rooms INNER JOIN dbo.roomtypes ON dbo.rooms.roomtype_id = dbo.roomtypes.roomtype_id  
WHERE 
(dbo.rooms.room_id NOT IN (SELECT 
room_id FROM dbo.booking)) 
AND(dbo.rooms.roomtype_id >= 4) 

回答

1

一種方法是GROUP BY

SELECT MAX(dbo.rooms.room_id),MAX(dbo.roomtypes.name), dbo.rooms.roomtype_id 
FROM dbo.rooms INNER JOIN dbo.roomtypes ON dbo.rooms.roomtype_id = dbo.roomtypes.roomtype_id 
WHERE (dbo.rooms.room_id NOT IN (SELECT room_id FROM dbo.booking)) 
AND(dbo.rooms.roomtype_id >= 4) 
GROUP BY dbo.rooms.roomtype_id 
+0

謝謝,這正是我所需要的。 – Shuffz 2011-03-28 15:08:37

+0

@Shuffz - 樂於幫忙 – JNK 2011-03-28 15:09:10

+0

@Andriy M--會做! – Shuffz 2011-04-02 21:11:53

2

採用DISTINCT是另一種選擇:

SELECT DISTINCT dbo.rooms.roomtype_id 
FROM dbo.rooms INNER JOIN dbo.roomtypes ON dbo.rooms.roomtype_id = dbo.roomtypes.roomtype_id 
WHERE (dbo.rooms.room_id NOT IN (SELECT room_id FROM dbo.booking)) 
AND(dbo.rooms.roomtype_id >= 4)