Skip to content
Advertisement

Concat SQL result

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
  1. how do I iterate the query through every room ID that matches the filter conditions
  2. how to merge both queries into a single query
  3. how would I go about concatenating the values as “OCCUPANTS / PAX” into a single column

Any help is appreciated.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement