我想从下面的示例数据中选择不同的建筑名称,其中Y与N的比率等于或大于75%。
CREATE TABLE Table1
(`UID` int, `Building Name` varchar(10), `Pets` varchar(1));
INSERT INTO Table1
(`UID`, `Building Name`, `Pets`) VALUES
(1, 'Building A', 'Y'),
(2, 'Building A', 'Y'),
(3, 'Building A', 'Y'),
(4, 'Building A', 'N'),
(5, 'Building B', 'Y'),
(6, 'Building B', 'Y'),
(7, 'Building B', 'N'),
(8, 'Building B', 'N'),
(9, 'Building C', 'N'),
(10, 'Building C', 'N'),
(11, 'Building C', 'Y'),
(12, 'Building C', 'Y'),
(13, 'Building C', 'N');
最佳答案
在MySQL中,如果您说SUM(Pets = 'Y')
,则会得到Pets
列值为Y
的行数。这是因为布尔表达式的值为0(false)或1(true)。
所以您的查询是一个简单的聚合。(http://sqlfiddle.com/#!9/077e1/31/0)
SELECT `Building name`, COUNT(*) cnt, SUM(Pets = 'Y') Pets ,
100.0 * SUM(Pets = 'Y') / COUNT(*) percent
from table1
group by `Building name`
having 100.0 * SUM(Pets = 'Y') / COUNT(*) >= 75.0
如果您想要跨表服务器的可移植性,就不能依赖
SUM(boolean)
技巧。您需要(http://sqlfiddle.com/#!9/077e1/37/0)这个查询。SELECT `Building name`, COUNT(*) cnt, SUM(CASE WHEN Pets = 'Y' THEN 1 ELSE 0 END) Pets ,
100.0 * SUM(CASE WHEN Pets = 'Y' THEN 1 ELSE 0 END) / COUNT(*) percent
from table1
group by `Building name`
having 100.0 * SUM(CASE WHEN Pets = 'Y' THEN 1 ELSE 0 END) / COUNT(*) >= 75.0
这两个行的执行情况大致相同;第二个行的执行速度稍慢,但不太快,因为它们必须查看相同数量的行(即所有行)。