获得GROUP BY的第一个条件作为附加行?

时间:2015-04-05 17:05:03

标签: sql sql-server

我的sql字符串如下;

SELECT
            Country,
            City,
            COUNT(*) AS [Count]
        FROM
            CountiresAndCities
        GROUP BY
            Country, 
            City

我想获得国家的价值,因为没有使用UNION的额外行是可能的吗?

谢谢你。

2 个答案:

答案 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 

SQL Fiddle

答案 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