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;
How can i开发者_开发问答 make this request more effective?
it is possible with using WITH
. Move all queries to WITH
and modify them a little: change COUNT(cid)
to COUNT(DISTINCT cid)
and remove GROUP BY
clause at all.
You could use something like this:
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;
this query doesn't grouping by cid, but probably you don't need it.
精彩评论