-1

我有一个关于 sql 的问题。如果我有一张包含类似信息的表格:

  City       Code

New York      |  10A
New York      |  10A
New York      |  20A
L.A           |  20A
L.A           |  20A
Washington    |  30A 
Washington    |  30A 
Washington    |  20A 
San Francisco |  20A
San Francisco |  20A

使用查询:SELECT City, Code, COUNT(Code) FROM table GROUP BY City我可以得到以下结果:

 City         Code    Total

New York      |  10A     2
New York      |  20A     1
L.A           |  20A     2
Washington    |  30A     2
Washington    |  20A     1
San Francisco |  20A     2

问题是:如何仅提取每个城市中总数较高的行?

4

2 回答 2

1

假设 SQL Server 或具有排名功能的 DBMS:

SELECT * 
FROM  (SELECT City, Code,
              COUNT(Code) Count_, 
              RANK() OVER (PARTITION BY City ORDER BY COUNT(*) DESC) Rank_
       FROM  #test  
       GROUP BY City,Code
      ) sub
WHERE Rank_ = 1 ;

这将返回所有平局条目,例如在丹佛 3 路平局的情况下,您将获得以下信息:

DEN 10A 1, DEN 20A 1, Den 30A 1

SQL-Fiddle中测试。适用于 Oracle、Postgres、SQL-Server。

于 2013-05-24T23:04:04.883 回答
0

this worked for me:

SELECT     y.city, z.code, z.total
FROM       (SELECT city, MAX(total) AS total
            FROM (SELECT city, code, COUNT(code) AS total
                  FROM tableName
                  GROUP BY city, code) AS x
            GROUP BY city) AS y INNER JOIN
            (SELECT city, code, COUNT(code) AS total
             FROM tableName
             GROUP BY city, code) AS z
            ON y.city = z.city AND y.total = z.total

if there is a tie it will return all the rows that tied.

于 2013-05-25T18:02:51.197 回答