我试图选择每个“名字”的车数。如果我使用“distinct” 我只得到发生次数,不好。我需要得到类似的结果 这样:
Name NumberOfCars
Joe Doe 3
Mary Lou 2
Lou Ann 1
我的表/数据样本:
Control# Account# Name CarNumber CarYear CarFactory
X1111 112233A Joe Doe 1 2007 TOYOTA
X1111 112233A Joe Doe 1 2007 TOYOTA
X1111 112233A Joe Doe 1 2007 TOYOTA
X1111 112233A Joe Doe 2 2008 GMC S
X1111 112233A Joe Doe 2 2008 GMC S
X1111 112233A Joe Doe 2 2008 GMC S
X1111 112233A Joe Doe 3 2012 SPRIN
X1111 112233A Joe Doe 3 2012 SPRIN
X1111 112233A Joe Doe 3 2012 SPRIN
X1111 556688B Mary Lou 1 2003 JEEP
X1111 556688B Mary Lou 1 2003 JEEP
X1111 556688B Mary Lou 1 2003 JEEP
X1111 556688B Mary Lou 1 2003 JEEP
X1111 556688B Mary Lou 2 2004 TOYO
X1111 556688B Mary Lou 2 2004 TOYO
X1111 556688B Mary Lou 2 2004 TOYO
X1111 556688B Mary Lou 2 2004 TOYO
Y1112 882234C Lou Ann 2 2015 LEX
Y1112 882234C Lou Ann 2 2015 LEX
这是我的简单选择,我正在使用SQL Server:
SELECT distinct Name, CarNumber as NumberOfCars
FROM my_table
WHERE Control# in('X1111', Y1112)
有关如何做到这一点的任何建议? 谢谢你的期待!
答案 0 :(得分:1)
你只需要使用group by
计算不同的编号。
SELECT Name, count(distinct CarNumber) as NumberOfCars
FROM my_table
WHERE Control# in('X1111', 'Y1112')
group by name