SQL使用Count和Group By

时间:2014-05-02 16:03:09

标签: sql sql-server sql-server-2008

我必须根据State及其最近的订单选择客户总数,即DateFilled。

select CustomerLastName,CustomerFirstName, [State], DateFilled from customer


State  Total#CustByState    RecentDateFilled 
CA        100                04/01/2014
AZ        80                 04/23/2014
OR        120                02/02/2014

1 个答案:

答案 0 :(得分:3)

简单分组会为您提供计数和最新订单,当然这是该州任何客户的最新订单?

SELECT [State], COUNT(*) as TotalCusts, Max(DateFilled) as LastDateFilled
FROM Customer
GROUP By State;

如果您需要不同客户的数量(假设您桌子上的其他位置有一些关键字):

SELECT [State], COUNT(DISTINCT CustId) as TotalCusts, Max(DateFilled) as LastDateFilled
FROM Customer
GROUP By State;