0

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

顾客

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 子句中添加这些列?由于我只想按 CusID 对它们进行分组,我将如何选择这些列而不将它们包含在 Group By 中?

4

4 回答 4

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 :)
于 2013-09-19T18:33:34.883 回答
0

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

因为您说您需要对结果进行分组并为每个 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)或者如果其他列是一些数字(比如一个部门的薪水)左右,那么不在 group by 中的每一列都应该有一个聚合函数。

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

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

于 2013-09-19T02:48:35.427 回答
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;
于 2013-09-19T02:42:51.397 回答
0

我也发现第一个答案是最好的,但是在 SQL2005 CTE中出现了,它们可以帮助获得更好的可读性:

;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
于 2015-12-19T05:54:42.307 回答