分组依据3表连接SQL

时间:2016-10-06 21:56:33

标签: sql sql-server-2008

需要在3表连接上使用group by。我需要对按型号分组的汽车价格进行总结,并显示模型(和汽车)所属的类别

' Accord' 出现2次,总计为20,而'丰田' 也属于同一型号并总结在同一个模型中。最后只有1辆车的 Bellen' 。除了所有总价格和模型之外,每个模型的类别也按行显示。

enter image description here

我正在加入并总结价格作为以下查询,但显示错误,我假设是由第三个表列导致无法根据条件分组。我该如何获得所需的结果?

  

在选择列表中无效,因为它不包含在任何一个中   聚合函数或GROUP BY子句。

 SELECT sum(cars.price),models.model,categories.category 
FROM cars 
INNER JOIN 
models 
ON cars.mid=models.id 
inner join 
categories 
on models.model=categories.model 
group by models.model ORDER BY cars.name

1 个答案:

答案 0 :(得分:2)

假设图表中的表名/列名是正确的

数据:

CREATE TABLE car (price INT, name NVARCHAR(128), mid INT)
GO

INSERT INTO car
VALUES  (10, 'Accord', 1),
        (10, 'Accord', 1),
        (30, 'Bellen', 3),
        (40, 'Toyota', 1)
GO

CREATE TABLE models (id INT, model INT)
GO

INSERT INTO models
VALUES  (1, 1889),
        (2, 1999),
        (3, 2000)
GO

CREATE TABLE categories (model INT, category NVARCHAR(128))
GO

INSERT INTO categories
VALUES  (1889, '800 cc'),
        (1999, '1200 cc'),
        (2000, '1500 cc')
GO

查询:

SELECT sum(car.price) "Sum Price", models.model "Model", categories.category "Category" 
FROM car 
INNER JOIN models ON car.mid=models.id 
INNER JOIN categories ON models.model=categories.model 
GROUP BY models.model, categories.category
ORDER BY models.model, categories.category

结果:

Sum Price   Model   Category
60          1889    800 cc
30          2000    1500 cc