按列的SQL计数功能

时间:2013-07-22 01:45:22

标签: sql sql-server tsql

CusID   Order
3001    Hotdog
3001    Sausage
3002    Sausage
3003    Burger
3003    Hotdog
3002    Hotdog
3001    Burger

我将如何使用此计数功能?

SELECT COUNT(CusID) AS NumOfOrders FROM Orders

期望的输出

CusID   NumOfOrders
3001    3
3002    2
3003    2

4 个答案:

答案 0 :(得分:6)

您需要group by

SELECT CusId, COUNT(CusID) AS NumOfOrders
FROM Orders
group by CusId
order by CusId;

答案 1 :(得分:1)

group by会为您提供所需的结果以及Count功能。

select CustID, count(CustID) from Orders
group by CustID

请参阅下面的小提琴链接样本

SQL Fiddle

答案 2 :(得分:0)

select CusID,count(CusID) from Orders group by CusID order by CusId

答案 3 :(得分:0)

尝试在查询中添加GROUP BYORDER BY

SELECT CusId, COUNT(CusID) AS NumOfOrders
FROM Orders
GROUP BY CusId
ORDER BY CusId;