简体   繁体   中英

Combine two MySQL queries to display one unique value and an AVG value for each column

Is there a way to combine two MySQL queries to display one unique value and an AVG value for each column? Such as in this query:

SELECT `price`, `cost`, `shipping` 
FROM `orders` 
WHERE `year` = 2019 AND `product_id` = 5 AND `order_id` = 77 
LIMIT 1

WITH

SELECT AVG(`price`), AVG(`cost`), AVG(`shipping`) 
FROM `orders` 
WHERE `year` = 2019 AND `product_id` = 5

I've been playing with unions and joins but I'm not finding a way to return this data in the same query. (I can make two separate queries and put the resulting data side-by-side, but I'd prefer to do it with one query if possible.)

Any ideas?

Since both queries return just one record, you could just turn them to subqueries and CROSS JOIN them :

SELECT a.price, a.cost, a.shipping, avg.price, avg.cost, avg.shipping 
FROM 
    ( 
        SELECT `price`, `cost`, `shipping` 
        FROM `orders` 
        WHERE `year` = 2019 AND `product_id` = 5 AND `order_id` = 77 
        LIMIT 1 
    ) a
    CROSS JOIN ( 
        SELECT AVG(`price`) price, AVG(`cost`) cost, AVG(`shipping`) shipping 
        FROM `orders` 
        WHERE `year` = 2019 AND `product_id` = 5 
    ) avg

The purpose of the LIMIT 1 clause in the first subquery is unclear : since there is no ORDER BY , it is unpredictable which record will be returned if more than one matches.

Here is an alternative approach using conditional aggregation (if several record exist with order id 77 , the maximum value of each column will be displayed) :

SELECT
    MAX(CASE WHEN `order_id` = 77 THEN `price` END) price,
    MAX(CASE WHEN `order_id` = 77 THEN `cost` END) cost,
    MAX(CASE WHEN `order_id` = 77 THEN `shipping` END) shipping,
    AVG(`price`) avg_price, 
    AVG(`cost`) avg_cost,
    AVG(`shipping`) avg_shipping
FROM `orders`
WHERE `year` = 2019 AND `product_id` = 5

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