简体   繁体   English

SQL子查询返回排名2

[英]SQL subquery to return rank 2

I have a question about writing a sub-query in Microsoft T-SQL. 我有一个关于在Microsoft T-SQL中编写子查询的问题。 From the original table I need to return the name of the person with the second most pets. 从原始表中,我需要返回宠物第二多的人的名字。 I am able to write a query that returns the number of perts per person, but I'm not sure how to write a subquery to return rank #2. 我能够编写一个查询,该查询返回每人的位数,但是我不确定如何编写子查询以返回排名2。

Original table: 原始表格:

+—————————-——+———-————-+
|   Name     |  Pet    | 
+————————————+————-————+
| Kathy      |  dog    | 
| Kathy      |  cat    |
| Nick       |  gerbil | 
| Bob        |  turtle | 
| Bob        |  cat    | 
| Bob        |  snake  | 
+—————————-——+—————-———+

I have the following query: 我有以下查询:

SELECT Name, COUNT(Pet) AS NumPets
FROM PetTable
GROUP BY Name
ORDER BY NumPets DESC

Which returns: 哪个返回:

+—————————-——+———-————-+
|   Name     | NumPets | 
+————————————+————-————+
| Bob        |  3      | 
| Kathy      |  2      | 
| Nick       |  1      | 
+—————————-——+—————-———+

The ANSI standard method is: ANSI标准方法是:

OFFSET 1 FETCH FIRST 1 ROW ONLY

However, most databases have their own syntax for this, using limit , top or rownum . 但是,大多数数据库对此都有自己的语法,使用limittoprownum You don't specify the database, so I'm sticking with the standard. 您没有指定数据库,所以我坚持使用标准。

You are using TSQL So: 您正在使用TSQL所以:

WITH C AS (
    SELECT  COUNT(Pet) OVER (PARTITION BY Name) cnt
            ,Name
    FROM PetTable
)
SELECT TOP 1 Name, cnt AS NumPets
FROM C
WHERE cnt = 2

This is how you could use ROW_NUMBER to get the result. 这样便可以使用ROW_NUMBER获得结果。

SELECT *
FROM(
SELECT ROW_NUMBER() OVER (ORDER BY COUNT(name) DESC) as RN, Name, COUNT(NAME) AS COUNT
FROM PetTable
GROUP BY Name
) T
WHERE T.RN = 2

In MSSQL you can do this: 在MSSQL中,您可以执行以下操作:

SELECT PetCounts.Name, PetCounts.NumPets FROM (
  SELECT
    RANK() OVER (ORDER BY COUNT(Pet) DESC) AS rank,
    Name, COUNT(Pet)as NumPets
  FROM PetTable
  GROUP BY Name
) AS PetCounts
WHERE rank  = 2

This will return multiple rows if they have the same rank. 如果它们具有相同的排名,则将返回多个行。 If you want to return just one row you can replace RANK() with ROW_NUMBER() 如果您只想返回一行,则可以用ROW_NUMBER()替换RANK()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM