我有一张桌子:Country Varchar(20),City Varchar(20),Street Varchar(20)
我想计算所有城市的街道,如果其中一个是主街
它应该是这样的......
SELECT Country, City, Count(Street)
FROM Streets
GROUP BY Country, City;
我不知道如何检查其中一个街道名称是否是Main Street我该怎么办?
答案 0 :(得分:4)
您可以使用having
:
SELECT Country, City, Count(Street)
FROM Streets
GROUP BY Country, City
HAVING SUM(CASE WHEN Street = 'Main Street' THEN 1 ELSE 0 END) > 0;
答案 1 :(得分:0)
你可以简单地使用它。
SELECT Country, City, Count(Street) FROM Streets where upper(streets)='MAIN STREET' GROUP BY Country, City;
答案 2 :(得分:0)
您可以在WHERE子句中使用子查询来查找所有拥有主街的城市:
SELECT COUNTRY, CITY, COUNT(STREETS)
FROM STREETS
WHERE (COUNTRY, CITY) IN (SELECT DISTINCT COUNTRY, CITY
FROM STREETS
WHERE UPPER(STREET) = 'MAIN STREET')
GROUP BY COUNTRY, CITY
或者您可以使用联接
SELECT s.COUNTRY, s.CITY, COUNT(s.STREETS)
FROM STREETS s
INNER JOIN (SELECT DISTINCT COUNTRY, CITY
FROM STREETS
WHERE LOWER(STREET) = 'main street') c
ON c.COUNTRY = s.COUNTRY AND
c.CITY = s.CITY
或者您可以使用公用表表达式:
WITH cteCITIES_WITH_MAIN_STREET AS (SELECT DISTINCT COUNTRY, CITY
FROM STREETS
WHERE INITCAP(STREET) = 'Main Street')
SELECT s.COUNTRY, s.CITY, COUNT(s.STREETS)
FROM STREETS s
INNER JOIN cteCITIES_WITH_MAIN_STREET c
ON c.COUNTRY = s.COUNTRY AND
c.CITY = s.CITY
注意:未在动物身上进行过测试;你会先成为第一个! : - )
祝你好运。