SELECT
COUNT(a)/COUNT(s)*100 as aratio,
COUNT(b)/COUNT(s)*100 as bratio,
COUNT(c)/COUNT(s)*100 as cratio,
COUNT(a),
COUNT(b),
COUNT(c),
COUNT(s)
FROM
(SELECT COUNT(cid) as a FROM images WHERE width > height AND category_id = 4 GROUP BY cid) as aq,
(SELECT COUNT(cid) as b FROM images WHERE width < height AND category_id = 4 GROUP BY cid) as bq,
(SELECT COUNT(cid) as c FROM images WHERE width = height AND category_id = 4 GROUP BY cid) as cq,
(SELECT COUNT(cid) as s FROM images WHERE category_id = 4 GROUP BY cid) as sq;
如何才能使此请求更有效?
答案 0 :(得分:1)
可以使用WITH
。将所有查询移至WITH
并稍加修改:将COUNT(cid)
更改为COUNT(DISTINCT cid)
并删除GROUP BY
条款。
答案 1 :(得分:1)
您可以使用以下内容:
SELECT
SUM(CASE (width > height) WHEN true THEN 1 ELSE 0 END)::float8*100/COUNT(*) as aratio,
SUM(CASE (width < height) WHEN true THEN 1 ELSE 0 END)::float8*100/COUNT(*) as bratio,
SUM(CASE (width = height) WHEN true THEN 1 ELSE 0 END)::float8*100/COUNT(*) as cratio,
SUM(CASE (width > height) WHEN true THEN 1 ELSE 0 END),
SUM(CASE (width < height) WHEN true THEN 1 ELSE 0 END),
SUM(CASE (width = height) WHEN true THEN 1 ELSE 0 END),
COUNT(*)
FROM
images WHERE category_id = 4;
此查询不按cid分组,但可能您不需要它。