查询错误,在选择列表中无效

时间:2018-04-17 11:44:37

标签: sql sql-server

我正在尝试根据旧的Northwind数据库编写aquery。我的任务是写一个查询,这将给我“按类别和供应商大陆库存的单位数量”。我写过这样的话:

    SELECT  Categories.CategoryName as "Categories",
        CASE WHEN Suppliers.Country in 
        ('UK','Spain','Sweden','Germany','Norway',
                  'Denmark','Netherlands','Finland','Italy','France')
            THEN 'Europe'
            WHEN Suppliers.Country in
             ('USA', 'Brazil','Canada')
            THEN 'America'
            ELSE 'Asia-Pacific' 
            END AS "Supplier Continent", 
        sum(Products.UnitsInStock) as "Units In Stock"
FROM Suppliers
INNER JOIN Products ON Products.SupplierID=Suppliers.SupplierID
INNER JOIN Categories ON Categories.CategoryID= Products.CategoryID
GROUP BY Categories.CategoryName;

可悲的是,MS SQL Server Management Studio引发了一个错误:

  

Msg 8120,Level 16,State 1,Line 165

     

列'Suppliers.Country'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

我应该更改什么来修复此错误并使我的查询有效?

1 个答案:

答案 0 :(得分:1)

将原始查询包装在派生表中。汇总其结果:

select "Categories", "Supplier Continent", sum("UnitsInStock") as "Units In Stock"
from
(
    SELECT  Categories.CategoryName as "Categories",
            CASE WHEN Suppliers.Country in 
            ('UK','Spain','Sweden','Germany','Norway',
                      'Denmark','Netherlands','Finland','Italy','France')
                THEN 'Europe'
                WHEN Suppliers.Country in
                 ('USA', 'Brazil','Canada')
                THEN 'America'
                ELSE 'Asia-Pacific' 
                END AS "Supplier Continent", 
            Products.UnitsInStock as "UnitsInStock" 
    FROM Suppliers
    INNER JOIN Products ON Products.SupplierID=Suppliers.SupplierID
    INNER JOIN Categories ON Categories.CategoryID= Products.CategoryID
) dt
GROUP BY "Categories", "Supplier Continent";