我在SQL Server Management Studio 2012中的简单查询如下: -
SELECT Last_Name, City,
(SELECT COUNT (City) FROM Customers IX WHERE IX.City = EX.City) as counting
FROM Customers EX
GROUP BY City, Last_Name
ORDER BY City
输出: -
Last_Name City Counting
Joe London 3
Smith London 3
Carter London 3
Stones New York 3
Jones New York 3
White New York 3
但我希望它不要重复同一个城市的计数和输出如下: -
Last_Name City Counting
Joe London 3
Smith London
Carter London
Stones New York 3
Jones New York
White New York
我将如何实现这一目标?
答案 0 :(得分:1)
看起来像一个非常奇怪的请求,并且很容易在应用程序端完成。但是在SQL中并不难:
SELECT Last_Name, City,
(case when row_number() over (partition by Last_Name, City order by (select NULL)) = 1
then (SELECT COUNT(City) FROM Customers IX WHERE IX.City = EX.City) as counting
end) as Counting
FROM Customers EX
GROUP BY City, Last_Name
ORDER BY City;
这会将值放在每个城市的一行上。它不是确定哪一个,但可能是实践中的第一个。您可以通过使用稳定的排序来保证这一点:
SELECT Last_Name, City,
(case when row_number() over (partition by Last_Name, City order by Last_Name) = 1
then (SELECT COUNT(City) FROM Customers IX WHERE IX.City = EX.City) as counting
end) as Counting
FROM Customers EX
GROUP BY City, Last_Name
ORDER BY City, Last_Name