我有以下查询来计算数据库中的设备数量。我尝试添加WHERE子句以仅选择设备并使用名称“iphone”进行计数。
SELECT device, count( * ) AS count, sum( 100 ) / total AS percentage
FROM devices WHERE device='apple'
CROSS JOIN (
SELECT count( * ) AS total
FROM devices
)x
GROUP BY 1
我尝试构造不同的查询,但它们都会导致mysql错误。 WHERE子句的正确位置是什么?
答案 0 :(得分:2)
WHERE
在 FROM
之后和GROUP BY
之前
答案 1 :(得分:0)
SELECT device, count( * ) AS count, sum( 100 ) / total AS percentage
FROM devices
INNER JOIN (
SELECT count( * ) AS total
FROM devices
)x
WHERE device='apple'
GROUP BY 1
答案 2 :(得分:0)
顺便说一句,您可以将此查询重写为:
SELECT 'apple' as device, sum(device = 'apple') AS count,
100 * sum(device = 'apple') / count(*) AS percentage
FROM devices ;
这会删除额外的表扫描以计算总数和join
(这非常便宜,因为x
中只有一行。
答案 3 :(得分:0)
分组之前和之后的地方并加入:
SELECT device, count( * ) AS count, sum( 100 ) / total AS percentage
FROM devices
CROSS JOIN (
SELECT count( * ) AS total
FROM devices
)x
WHERE device='apple'
GROUP BY 1