SQL-ex.ru#26从两个表中搜索平均值

时间:2013-03-27 05:37:49

标签: sql join union

我在网站http://www.sql-ex.ru/上有一个关于SQL查询的问题。查询要求 :

  

定义制造商A生产的PC和笔记本电脑的平均价格。

数据库架构如下:

Product(maker, model, type)
PC(code, model, speed, ram, hd, cd, price)
Laptop(code, model, speed, ram, hd, screen, price)
Printer(code, model, color, type, price)

我将我的查询写成:

SELECT AVG(t.k) AS Avg_Price
FROM
  (SELECT AVG(A.price) AS k
    FROM PC A 
  JOIN Product B ON(A.model=B.model)
  WHERE B.maker='A'
  UNION ALL
  SELECT AVG(C.price) AS k
     FROM Laptop C
  JOIN PRODUCT D ON(C.model=D.model)
  WHERE D.maker='A') AS t

问题是它没有返回正确的答案。返回的平均值远高于预期。计算平均值的方式是错误的吗?如何更改查询以便返回预期的答案?任何帮助将不胜感激。

由于

11 个答案:

答案 0 :(得分:4)

您分别对PC价格和笔记本电脑价格进行平均,然后将平均值平均在一起。您的查询很好,除非您不应该在子查询中平均价格。只需返回子查询中的价格并在顶级平均值:

select
    AVG( Price ) Avg_Price
from
(
    (
        select
            pc.Price
        from
            PC pc
            join Produt prod
             on pc.Model = prod.Model
        where
            prod.Maker = 'A'
    )
    union all
    (
        select
            pc.Price
        from
            Laptop l
            join Produt prod
             on l.Model = prod.Model
        where
            prod.Maker = 'A'
    )
) q

答案 1 :(得分:3)

SELECT AVG(datatable.price) FROM
(
(SELECT PC.Price FROM PC INNER JOIN Product p1 ON PC.model=P1.model     
     WHERE P1.maker='A') 
UNION ALL 
(SELECT Laptop.price FROM Laptop INNER JOIN Product p2 ON 
    Laptop.model=P2.model WHERE P2.maker='A')
) datatable

右。

您的查询结果:

  

Avg_Price

     

754.1666

答案 2 :(得分:2)

您的查询错误。它通常与您在分布式系统上聚合的方式类似。您可以在分布式节点上进行聚合,然后恢复聚合数据并在返回数据之上进行聚合,只有聚合可以转移。 AVG 不可转换。 (1 + 2 + 3 + 4 + 5)/ 5< 1 + 2 + 3 + 4 + 5)/ 5< ((1 + 2)/ 2 +(1 + 2 + 3)/ 3)

答案 3 :(得分:1)

也可以

SELECT Avg(price) AS avg_price
FROM   (SELECT pc.price
        FROM   pc
               INNER JOIN product
                       ON pc.model = product.model
        WHERE  maker = 'A'
        UNION ALL
        SELECT laptop.price
        FROM   laptop
               INNER JOIN product
                       ON laptop.model = product.model
        WHERE  maker = 'A') Any_name 

答案 4 :(得分:0)

SELECT AVG(resultList.Price)
FROM
    (
        SELECT  a.Price
        FROM    PC a INNER JOIN Product B 
                    on a.Model = B.Model
        WHERE   B.Maker = 'A'
        UNION ALL
        SELECT  c.Price
        FROM    Laptop c INNER JOIN Product d 
                    on c.Model = d.Model
        WHERE   d.Maker = 'A'
    ) resultList

答案 5 :(得分:0)

select AVG(P.price) as avg_price
from
(
 select price, model from PC
 UNION ALL
 select price, model from Laptop
) P
join Product ON P.model = Product.model
where maker = 'A'

答案 6 :(得分:0)

with t1 as
(SELECT price, type from pc left join product on product.model = pc.model where maker = 'A'
UNION ALL
SELECT price, type from laptop left join product on product.model = laptop.model where maker = 'A')
select avg(price) from t1

答案 7 :(得分:0)

SELECT AVG(price) FROM 
(
     SELECT PC.price, Product.maker FROM PC JOIN Product ON(PC.model=Product.model)
     UNION ALL
     SELECT Laptop.price, Product.maker FROM Laptop JOIN Product ON (Laptop.model = Product.model)
) T 
GROUP BY T.maker HAVING T.maker = 'A'

这很有效,因为首先你选择所有的笔记本电脑和电脑价格,然后你只选择制造商='A'的记录,最后一步是计算平均价格。

答案 8 :(得分:0)

Select avg(price) from
       ((select price,model  from pc 
       union all
       select price,model from laptop) a inner join  product on product.model=a.model and product.maker='A' )

首先,我认为最好同时使用两个表的union pricemodel,然后再从制造商A中找到average(price)

答案 9 :(得分:0)

我一直都非常努力地与JOINS(个人)打交道,因此请尝试不使用联接的解决方案。 使用IN运算符

ParseError
syntax error, unexpected end of file
1. in /home/u7796600/public_html/views/mahasiswa/_form.phpat line 152
143144145146147148149150151    });
 
    JS;
 
    $this->registerJs($script,
        yii\web\View::POS_END,
        'in-x-handler'
    );?>
</div>
2. in /home/u7796600/public_html/vendor/yiisoft/yii2/base/View.php at line 257– yii\base\View::renderPhpFile('/home/u7796600/public_html/views...', ['model' => app\models\Mahasiswa])
3. in /home/u7796600/public_html/vendor/yiisoft/yii2/base/View.php at line 156– yii\base\View::renderFile('/home/u7796600/public_html/views...', ['model' => app\models\Mahasiswa], null)
4. in /home/u7796600/public_html/views/mahasiswa/create.php at line 16– yii\base\View::render('_form', ['model' => app\models\Mahasiswa])
101112131415161718$this->params['breadcrumbs'][] = $this->title;
?>
<div class="mahasiswa-create" style="margin-left: 100px;margin-right: 100px;">
 
    <h1><?= Html::encode($this->title) ?></h1>
    <hr>
    <?= $this->render('_form', ['model' => $model]) ?>
 
</div>
5. in /home/u7796600/public_html/vendor/yiisoft/yii2/base/View.php at line 348– require('/home/u7796600/public_html/views...')
6. in /home/u7796600/public_html/vendor/yiisoft/yii2/base/View.php at line 257– yii\base\View::renderPhpFile('/home/u7796600/public_html/views...', ['model' => app\models\Mahasiswa])
7. in /home/u7796600/public_html/vendor/yiisoft/yii2/base/View.php at line 156– yii\base\View::renderFile('/home/u7796600/public_html/views...', ['model' => app\models\Mahasiswa], app\controllers\MahasiswaController)
8. in /home/u7796600/public_html/vendor/yiisoft/yii2/base/Controller.php at line 409– yii\base\View::render('create', ['model' => app\models\Mahasiswa], app\controllers\MahasiswaController)
9. in /home/u7796600/public_html/controllers/MahasiswaController.php at line 106– yii\base\Controller::render('create', ['model' => app\models\Mahasiswa])
100101102103104105106107108109110111112                    $model->addError('foto', "Foto tidak boleh kosong !");
                }
            }
        }
 
        return $this->render('create', [
            'model' => $model,
        ]);
    }
 
    /**
     * Updates an existing Mahasiswa model.
     * If update is successful, the browser will be redirected to the 'view' page.
10. app\controllers\MahasiswaController::actionCreate()
11. in /home/u7796600/public_html/vendor/yiisoft/yii2/base/InlineAction.php at line 57– call_user_func_array([app\controllers\MahasiswaController, 'actionCreate'], [])
12. in /home/u7796600/public_html/vendor/yiisoft/yii2/base/Controller.php at line 180– yii\base\InlineAction::runWithParams([])
13. in /home/u7796600/public_html/vendor/yiisoft/yii2/base/Module.php at line 528– yii\base\Controller::runAction('create', [])
14. in /home/u7796600/public_html/vendor/yiisoft/yii2/web/Application.php at line 103– yii\base\Module::runAction('mahasiswa/create', [])
15. in /home/u7796600/public_html/vendor/yiisoft/yii2/base/Application.php at line 386– yii\web\Application::handleRequest(yii\web\Request)
16. in /home/u7796600/public_html/index.php at line 12– yii\base\Application::run()
6789101112 
require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/vendor/yiisoft/yii2/Yii.php';
 
$config = require __DIR__ . '/config/web.php';
 
(new yii\web\Application($config))->run();
$_COOKIE = [
    '_csrf' => '88604fb700879268611516c1ee39de9cdab11ea7f454885b6bf3328fb9d26e97a:2:{i:0;s:5:"_csrf";i:1;s:32:"bNGjdI0AfMr2cromPF1xm1f7RthBqbIf";}',
    '_identity-admin-simpresensi' => '["admin","jKDGomSH1sCM3KRg2zooF97hI6MbsNHN",2592000]',
    'PHPSESSID' => '021088dcd0c061b02965e21ab8d87fcb',
];

$_SESSION = [
    '__flash' => [],
    'admin' => 'admin',
];

答案 10 :(得分:-1)

select avg(price) as avg_price from
(select price
from Product, PC
where Product.model = PC.model
and maker = 'A'
union all
select price
from Product, Laptop
where Product.model = Laptop.model
and maker='A') avg_price