[英]MySQL query to calculate a ratio using a subset of rows from a table
I have a simple table SeatTracking that tracks the number of seats used in a given room.我有一个简单的表 SeatTracking,用于跟踪给定房间中使用的座位数。 The table has three columns: roomID, type, value.
该表包含三列:roomID、type、value。
Here's an example of the data:以下是数据示例:
roomID![]() |
type![]() |
value![]() |
---|---|---|
1001 ![]() |
occupied![]() |
20 ![]() |
1001 ![]() |
vacant![]() |
10 ![]() |
1002 ![]() |
occupied![]() |
5 ![]() |
1002 ![]() |
vacant![]() |
95 ![]() |
I know how to write a query returning the total number of seats in each room.我知道如何编写查询返回每个房间的总座位数。
SELECT roomID,SUM(value) AS total_seats FROM SeatTracking GROUP BY roomID;
I also know how to write a query returning the total number of vacant seats in each room.我也知道如何编写查询返回每个房间的空位总数。
SELECT roomID,SUM(CASE type WHEN 'vacant' THEN value END) AS vacant_seats FROM SeatTracking GROUP BY roomID;
Here's the part I'm struggling with - I want to return a vacancy rate for each room.这是我正在努力解决的部分 - 我想返回每个房间的空置率。 Can someone please point me in the right direction here?
有人可以在这里指出我正确的方向吗? Thank you!
谢谢!
I tried the below but I get an error - "you have an error in your SQL syntax:
我尝试了以下但出现错误 -
"you have an error in your SQL syntax:
SELECT roomID, (SUM(CASE type WHEN 'vacant' THEN value END)/SUM(CASE type WHEN 'occupied' THEN value END))*100 AS vacancy_rate
FROM SeatTracking GROUP BY roomID;
I also tried being more explicit, but I get an error unknown column vacant_seats in field list:我也尝试过更明确,但我在字段列表中收到错误 unknown column vacant_seats :
SELECT roomID, SUM(CASE type WHEN 'vacant' THEN value END) AS vacant_seats,
SUM(CASE type WHEN 'occupied' THEN value END) AS occupied_seats,
(vacant_seats/occupied_seats)*100 AS vacancy_rate
FROM SeatTracking GROUP BY roomID;
SELECT
(SUM
(
CASE type
WHEN 'vacant' THEN value
END
) / SUM(
CASE type
WHEN 'occupied' THEN value
END
) * 100
) AS vacancy_rate
FROM
SeatTracking;
Simplest query that will work.最简单的查询。 Query output here
在这里查询output
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.