我的sql字符串如下;獲取GROUP BY的第一個條件作爲附加行嗎?
SELECT
Country,
City,
COUNT(*) AS [Count]
FROM
CountiresAndCities
GROUP BY
Country,
City
我想獲得國家的價值太多,因爲額外的行不使用UNION是可能的嗎?
謝謝你的忠告。
我的sql字符串如下;獲取GROUP BY的第一個條件作爲附加行嗎?
SELECT
Country,
City,
COUNT(*) AS [Count]
FROM
CountiresAndCities
GROUP BY
Country,
City
我想獲得國家的價值太多,因爲額外的行不使用UNION是可能的嗎?
謝謝你的忠告。
您可以使用GROUPING SETS
這個
SELECT Country,
City,
COUNT(*) AS [Count]
FROM CountiresAndCities
GROUP BY grouping sets ((Country, City), (Country))
ORDER BY grouping(City),
Country,
City
,我想出了是使用一個子查詢來計算國家和最簡單的辦法:
例子(使用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
你是什麼國家的價值是什麼意思?像COUNT(國家)? – SimplicityGuy 2015-04-05 17:08:38
這個字符串沒有返回國家和它的總數沒有聯盟 – Kerberos 2015-04-05 17:16:47