我正在运行查询,以便让学生按城市计算。
表格(Address
)包含学生的记录。地址信息。
AddressID, StudentID, Address, City, Country, Telephone
是地址表的一些字段。我必须说明一点:城市列值由7个字符组成。
每个城市都有一个以1开头的唯一偏移号码,前9个城市在开头就放松了0。
CASE I :如果学生居住在09市,如果该中心位于市中心,则其列为900000
。如您所见,小于10的城市代码有6个字符长度。
CASE II :如果学生居住在城市但位于城镇,城市代码会根据城镇的代码900001
而变化。
现在我通过下面的查询查询每个城市的学生人数,但我有一些城市的重复行。它带来了学生数量居住在市中心,并在一个城镇单独,所以我得到了一些这样的结果:
stuCnt cityCode
------ --------
102 01
240 02
21 03
54 03
SELECT COUNT(StudentID) AS stuCnt,
RIGHT('00' + ISNULL(LEFT(City, LEN(City) - 5), ''), 2) AS cityCode
FROM Address
GROUP BY City
ORDER BY City
如何获得如下结果?
stuCnt cityCode
------ --------
102 01
240 02
75 03
答案 0 :(得分:2)
您可以使用内部SELECT
中的第一个查询,并将这些结果与SUM
分组:
SELECT SUM(stuCnt) As stuCnt,
cityCode
FROM
(
SELECT COUNT(StudentID) AS stuCnt,
RIGHT('00' + ISNULL(LEFT(City, LEN(City) - 5), ''), 2) AS cityCode
FROM Address
GROUP BY City
) X
GROUP BY cityCode
ORDER BY cityCode
答案 1 :(得分:2)
我喜欢Cross Apply:比嵌套查询更快,比每次记录解析城市快3倍。
SELECT COUNT(StudentID) AS stuCnt, tmp1.cityCode
FROM Address
CROSS APPLY (SELECT RIGHT('00' + ISNULL(LEFT(City, LEN(City) - 5), ''), 2) cityCode) as Tmp1
GROUP BY cityCode
ORDER BY cityCode
答案 2 :(得分:1)
您只需按计算值分组:
select
count(StudentID) as stuCnt,
right('00' + isnull(left(City, len(City) - 5), ''), 2) as cityCode
from
address
group by
right('00' + isnull(left(City, len(City) - 5), ''), 2)
order by
right('00' + isnull(left(City, len(City) - 5), ''), 2)
在某些版本的SQL中,您可以按顺序使用cityCode,而不是重写计算:
select
count(StudentID) as stuCnt,
right('00' + isnull(left(City, len(City) - 5), ''), 2) as cityCode
from
address
group by
right('00' + isnull(left(City, len(City) - 5), ''), 2)
order by
cityCode