我的sql字符串如下;
SELECT
Country,
City,
COUNT(*) AS [Count]
FROM
CountiresAndCities
GROUP BY
Country,
City
我想获得国家的价值,因为没有使用UNION的额外行是可能的吗?
谢谢你。
答案 0 :(得分:3)
您可以将GROUPING SETS
用于此
SELECT Country,
City,
COUNT(*) AS [Count]
FROM CountiresAndCities
GROUP BY grouping sets ( ( Country, City ), ( Country ) )
ORDER BY grouping(City),
Country,
City
答案 1 :(得分:0)
我想出的最简单的解决方案是使用子查询来计算country-sum:
示例(使用SQLite):
CREATE TABLE Games ( Country TEXT, City TEXT );
INSERT INTO Games VALUES ( 'USA', 'New York' );
INSERT INTO Games VALUES ( 'USA', 'New York' );
INSERT INTO Games VALUES ( 'USA', 'New York' );
INSERT INTO Games VALUES ( 'USA', 'Los Angeles' );
INSERT INTO Games VALUES ( 'USA', 'Los Angeles' );
INSERT INTO Games VALUES ( 'USA', 'San Francisco' );
INSERT INTO Games VALUES ( 'USA', 'San Francisco' );
INSERT INTO Games VALUES ( 'France', 'Paris' );
INSERT INTO Games VALUES ( 'France', 'Paris' );
INSERT INTO Games VALUES ( 'France', 'Paris' );
INSERT INTO Games VALUES ( 'France', 'Paris' );
INSERT INTO Games VALUES ( 'Spain', 'Madrid' );
INSERT INTO Games VALUES ( 'Spain', 'Madrid' );
INSERT INTO Games VALUES ( 'Spain', 'Barcelona' );
.headers on
.mode column
SELECT Country, City, MIN(CountryCount) AS CountryCount, COUNT(*) AS CityCount
FROM CountiresAndCities JOIN (
SELECT Country, COUNT(*) AS CountryCount
FROM CountiresAndCities GROUP BY Country
) USING (Country)
GROUP BY Country, City;
Country City CountryCount CityCount
---------- ---------- ------------ ----------
France Paris 4 4
Spain Barcelona 3 1
Spain Madrid 3 2
USA Los Angele 7 2
USA New York 7 3
USA San Franci 7 2