简体   繁体   English

选择包含特定列中前 N 个唯一值的行

[英]Select rows that contain the first N unique values in a certain column

For example, how do I select the rows that contain the first N=3 unique values in column X1?例如,如何选择包含 X1 列中前 N=3 个唯一值的行?

Observe the first 3 unique values in column X1 are apple, car, and egg.观察 X1 列中的前 3 个唯一值是苹果、汽车和鸡蛋。 How do I only select the rows that contain one of these values in column X1?如何仅选择包含 X1 列中这些值之一的行?

+----+---------+--------------+---------+
| X1      | X2                | X3      |
+---------+-------------------+---------+
| apple   | rob@hotmail.com   | 285     |
| apple   | geo@gmail.com     | 862     |
| car     | p6346@live.com    | 381     |
| egg     | simon@hotmail.com | -1058   |
| egg     | pierr@hotmail.com | 652     |
| egg     | j5@gmail.com      | 27      |
| grape   | peter@outlook.com | -1502   |
| grape   | ann@aol.com       | 621     |
| lime    | frank@gmail.com   | 501     |
| lime    | george@aol.com    | 314     |
| lime    | sam@gmail.com     | 615     |
| melon   | mike@hotmail.com  | 271     |
| melon   | jo@hotmail.com    | -97     |
| pear    | james@aol.com     | -97     |
+---------+-------------------+---------+

The desired result would be:想要的结果是:

+----+---------+--------------+---------+
| X1      | X2                | X3      |
+---------+-------------------+---------+
| apple   | rob@hotmail.com   | 285     |
| apple   | geo@gmail.com     | 862     |
| car     | p6346@live.com    | 381     |
| egg     | simon@hotmail.com | -1058   |
| egg     | pierr@hotmail.com | 652     |
| egg     | j5@gmail.com      | 27      |
+---------+-------------------+---------+

Note X1 is ordered alphabetically.注意 X1 按字母顺序排列。

You can use DENSE_RANK to achieve your required output as below-您可以使用 DENSE_RANK 来实现所需的输出,如下所示-

DEMO HERE 演示在这里

 SELECT * FROM 
 (
      SELECT *,
      DENSE_RANK() OVER(ORDER BY [X1]) RN
      FROM your_table
 )A
 WHERE RN <= 3

Use a derived table for which you get the top 3 distinct x1 and join it to the original table on matching x1 s.使用派生表,您可以获得前 3 个不同的x1并将其连接到匹配x1的原始表。

SELECT t.*
       FROM (SELECT DISTINCT
                    TOP (3)
                    ti.x1
                    FROM elbat ti
                    ORDER BY ti.x1) x
            INNER JOIN elbat t
                       ON t.x1 = x.x1;

Alternatively you can use the dense_rank() window function to assign a number to each record according to the order of its x1 .或者,您可以使用dense_rank()窗口函数根据x1的顺序为每个记录分配一个数字。

SELECT x.x1,
       x.x2,
       x.x3
       FROM (SELECT ti.x1,
                    ti.x2,
                    ti.x3,
                    dense_rank() OVER (ORDER BY ti.x1) rk
                    FROM elbat ti) x
       WHERE x.rk <= 3;

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

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