简体   繁体   中英

getting distinct mysql result of one field based on another field

I have this code:

select count(distinct affiliate_orders_id) as count
, sum(affiliate_value) as total
, sum(affiliate_payment) as payment 
from " . TABLE_AFFILIATE_SALES . " a 
    left join " . TABLE_ORDERS . " o on (a.affiliate_orders_id = o.orders_id)
where a.affiliate_orders_id = o.orders_id 
and o.orders_status >= " . AFFILIATE_PAYMENT_ORDER_MIN_STATUS . "
        ";

  $affiliate_sales_query= tep_db_query($affiliate_sales_raw);
  $affiliate_sales= tep_db_fetch_array($affiliate_sales_query);

So, $affiliate_sales['total'] = 128000 when in fact it should be 32000 becuase there are multiple affiliate_values and affiliate_orders_id. The affilaite_values some have the same values so these cannot be distinct. affilaite_orders_id have all unique values but there are multiple rows of this and needs to be distinct. Then the affiliate_values has to sum up based on the distinct rows of affiliate_orders_id to get an accurate sum.

I'm trying to get the sum of all affiliate_values bused on how many distinct affiliate_orders_id are in the table.

Based on your update I think this will get you what you're looking for. You need to use a subQuery

SELECT COUNT(a) COUNT, SUM(av) total, SUM(ap) aptotal
FROM (
    SELECT affiliate_orders_id a, affiliate_value av, SUM(affiliate_payment) AS ap
from " . TABLE_AFFILIATE_SALES . " a 
    left join " . TABLE_ORDERS . " o on (a.affiliate_orders_id = o.orders_id
    GROUP BY affiliate_orders_id, affiliate_value)
where a.affiliate_orders_id = o.orders_id 
and o.orders_status >= " . AFFILIATE_PAYMENT_ORDER_MIN_STATUS . ") a

Now this leads to a bigger question. Are you missing a join condition in your tables? Typically you shouldn't have duplicate date returned in a query, so I would suggest double checking your query is joining properly first.

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