简体   繁体   English

PostgreSQL的。 改善查询。 WITH

[英]PostgreSQL. Improve query. WITH

how can I improve my query? 如何改善查询?

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;

There is a problem because of 因为有一个问题

FULL OUTER JOIN menRating b ON a.train_type = b.train_type

If the left table "womenRating" will not have any value of train_type that the second table has, there will be a empty field, and my DENSE_RANK() will count that row as №1 如果左表“ womenRating”将不具有第二个表的train_type值,则将有一个空字段,并且我的DENSE_RANK()将将该行计为№1

Use conditional aggregation: 使用条件聚合:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM