列中的列无效

时间:2013-09-19 02:41:10

标签: sql tsql sql-server-2008-r2

我将如何正确地做到这一点:

客户

CusID, CusLname, CusFname, CusMname, CusAddress, CusEmailAdd

订单

OrderID,  Order,   CusID

SQL

Select  Count(OrderID), o.CusID, CusLname, CusFname, CusMname, CusAddress, CusEmailAdd
From Customer c 
Inner join
Order o
On c.CusID = o.CusID
Group By o.CusID

错误 Column 'CusLname, CusFname, CusMname, CusAddress, CusEmailAdd' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

为什么我需要在Group By Clause中添加这些列?我将如何选择这些列而不将它们放入Group By中,因为我只想通过CusID对它们进行分组?

4 个答案:

答案 0 :(得分:1)

有点不同的版本(来自Gordon Linoff建议):

select
     cnt, c.CusID, CusLname, CusFname, CusMname, CusAddress, CusEmailAdd
from Customer c 
join (
    select  
        count(OrderID) cnt, CusID
    from Order o 
    group by
        CusID
) o on
    c.CusID = o.CusID
order by
    c.CusID // ordering by OrderID and Order is out of logic :)

答案 1 :(得分:0)

只需将它们包含在group by子句中:

Select  Count(OrderID), o.CusID, CusLname, CusFname, CusMname, CusAddress, CusEmailAdd
From Customer c 
Inner join
Order o
On c.CusID = o.CusID
Group By o.CusID, CusLname, CusFname, CusMname, CusAddress, CusEmailAdd;

答案 2 :(得分:0)

  

为什么我需要在Group By Clause中添加这些列?

因为您说您需要对结果进行分组并为每个ID提供一个结果。 这给你留下了两个选择。

1)在客户级别获取所有详细信息,这是您在示例中所需要的。

Select  Count(OrderID), o.CusID, CusLname, CusFname, CusMname, CusAddress, CusEmailAdd
From Customer c 
Inner join
Order o
On c.CusID = o.CusID
Group By o.CusID, CusLname, CusFname, CusMname, CusAddress, CusEmailAdd;

2)或者,如果其他列是某些数字(比如某个部门的工资),那么不在该组中的每一列都应具有聚合函数。

select dept_id, sum(salary), max(salary), min(salary)
from dept
group by dept_id;

如果您希望每个分组列有一行,则需要指定如何聚合其他列。

答案 3 :(得分:0)

我也发现第一个答案是最好的,但是在SQL2005中CTEs出现了,它们可以帮助提高读写能力:

;with order_cte as (
    select count(OrderID) cnt, CusID
    from Order o 
    group by CusID
)
select cnt, c.CusID, CusLname, CusFname, CusMname, CusAddress, CusEmailAdd
from Customer c 
   join order_cte o on c.CusID = o.CusID
order by c.CusID