Reputation: 513
I'm quite new to SQL and I am using MS Access's ListBox component which requires a query to display data. The following are the tables involved to make the query:
TABLE: Blocks +----+--------+ | ID | B_Name | +----+--------+ | 1 | blockF | | 2 | blockE | . . . TABLE: Rooms +----+------+--------+-------+-----+---------+-------+------+ | ID | B_ID | R_Name | Floor | PAX | E_Wing | BTC_R | Male | +----+------+--------+-------+-----+---------+-------+------+ | 1 | 1 | Room 1 | 2 | 10 | TRUE | TRUE | TRUE | | 2 | 1 | Room 2 | 2 | 10 | TRUE | TRUE | TRUE | | 3 | 2 | Room 1 | 1 | 10 | TRUE | FALSE | FALSE| . . .
where B_ID is foreign key to blocks showing a 1 to many relationship among blocks and rooms and PAX being max amount of vacancies.
TABLE: UserGroups +----+------+-------+-----------+ | ID | R_ID | Group | Occupants | +----+------+-------+-----------+ | 1 | 1 | SQ 1 | 4 | | 2 | 1 | SQ 2 | 5 | . . .
where R_ID is foreign key to rooms showing a 1 to many relationship among rooms and usergroups
User can filter through rooms based on the conditions in columns Floor, E_Wing, BTC_R, MALE and B_ID.
My question is how do i display all the rooms based on the filter conditions and the resultant table such as this:
*for example when filter condition is B_ID = 1*
TABLE: Query Result +--------+--------------+ | R_Name | ComplexQuery | +--------+--------------+ | Room 1 | 0 / 10 | | Room 2 | 9 / 10 | . . . ComplexQuery : "TOTAL OCCUPANTS / PAX"
Progress I have made so far are separate queries
SELECT SUM(UserGroups.Occupants) FROM UserGroups WHERE UserGroups.R_ID = DESIRED_ID SELECT Rooms.PAX FROM Rooms WHERE Rooms.ID = DESIRED_ID
Any help is appreciated.
Upvotes: 0
Views: 283
Reputation: 20818
you can also use concatenation for your ComplexQuery column:
CONCAT(ISNULL(SUM(UG.Occupants, 0), ' / ', R.Pax)) as ComplexQuery
Upvotes: 0
Reputation: 62851
If I'm understanding your question correctly, you need to use LEFT JOIN, SUM, and GROUP BY. Here is some untested code -- I think you need parentheses around the join in Access:
SELECT R.R_Name, SUM(UG.Occupants) / R.Pax as PercentageOfRoomOccupied
FROM Rooms R
LEFT JOIN UserGroups UG ON R.Id = UG.R_Id
WHERE R.B_ID = 1
GROUP BY R.R_Name, R.Pax
Good luck.
Upvotes: 1