如何改善查询?
WITH womenRating AS ( SELECT count(train_type) as trainCount, train_type FROM trainRoutine
INNER JOIN client ON client.id = trainRoutine.client_id
WHERE client.gender = 'Woman'
GROUP BY train_type
ORDER BY trainCount DESC ),
menRating AS (
SELECT count(train_type) as trainCount, train_type FROM trainRoutine
INNER JOIN client ON client.id = trainRoutine.client_id
WHERE client.gender = 'Man'
GROUP BY train_type
ORDER BY trainCount DESC )
select a.train_type, DENSE_RANK() OVER (ORDER BY a.traincount DESC) as women, DENSE_RANK() OVER (ORDER BY b.traincount DESC) as men
FROM womenRating a
FULL OUTER JOIN menRating b ON a.train_type = b.train_type;
由于
而出现问题FULL OUTER JOIN menRating b ON a.train_type = b.train_type
如果左表“womenRating”没有第二个表所具有的train_type值,则会有一个空字段,而我的DENSE_RANK()会将该行计为№1
答案 0 :(得分:0)
使用条件聚合:
SELECT train_type,
sum( (c.gender = 'Woman')::int) as women_count,
sum( (c.gender = 'Man')::int) as men_count,
dense_rank() over (order by sum( (c.gender = 'Woman')::int) desc) as women_rank,
dense_rank() over (order by sum( (c.gender = 'Man')::int) desc) as men_rank
FROM trainRoutine tr INNER JOIN
client c
ON c.id = tr.client_id
GROUP BY train_type
ORDER BY trainCount DESC