简体   繁体   中英

PSQL: sum doesn't work on fields

I have this query which works:

SELECT 
partners.name, 
roles.name, 
(SELECT count(*) FROM partner_member_bindings WHERE roles.id = partner_member_bindings.role_id AND verify_status != 'pending') AS Num_verifications,
CAST(roles.price_partner / 100 AS money) AS partner_price
FROM partners
JOIN roles ON roles.partner_id = partners.id
ORDER BY partners.name, roles.name

What I want is to display an additional field showing the "partner_price * Num_verifications" value in dollars. Nothing I do works:

sum(Num_verifications * partner_price) returns that the Num_verification doesn't exist. Copying over the whole sub-query (yes, i know, but I'm just testing) also doesn't work.

How can this be done?

The fields in select can only contain input columns and they become output columns when they are run. That is why you cannot use a computed column in another column definition.

But if you want a SUM that would mean some kind of aggregation. If you want the total sum of the multiplication of the fields, that is not usually done per row. Or do you only need the multiplication result? That is usually done in the presentation layer.

If you only need the multiplication (since there is no GROUP BY the SUM would be that anyway) you can put the whole query into a subquery and calculate from that, leaving the sorting outside:

SELECT
partnername,
rolename,
Num_verifications,
partner_price,
partner_price*Num_verifications
FROM
  (SELECT 
   partners.name as partnername, 
   roles.name as rolename, 
   (SELECT count(*) FROM partner_member_bindings WHERE roles.id = partner_member_bindings.role_id AND verify_status != 'pending') AS Num_verifications,
   CAST(roles.price_partner / 100 AS money) AS partner_price
   FROM partners
   JOIN roles ON roles.partner_id = partners.id) temp
ORDER BY partners.name, roles.name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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