简体   繁体   English

结合两个MySQL查询以为每个列显示一个唯一值和一个AVG值

[英]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? 有没有一种方法可以结合两个MySQL查询来为每个列显示一个唯一值和一个AVG值? 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 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 : 由于两个查询都只返回一条记录,因此您可以将它们转换为子查询,然后CROSS JOIN它们:

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. 第一个子查询中LIMIT 1子句的用途尚不清楚:由于没有ORDER BY ,因此如果多个匹配项返回哪条记录是不可预测的。

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) : 这是一种使用条件聚合的替代方法(如果存在多个订单ID为77记录,那么将显示每列的最大值):

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

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

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