如何在SQL的仅一列中选择没有重复的记录?

时间:2019-03-10 02:14:40

标签: mysql sql select duplicates

我有一个包含3列的表格,如下所示:

+------------+---------------+-------+  
| Industry      | country    | price |  
+------------+---------------+-------+  
Retail          |UK              | 20
Retail          | Japan          | 30
Retail          | Germany        | 40
Retail          | America        | 50

我想要的结果是这样的:

+------------+---------------+-------+  
| Industry      |    country  | price |  
+------------+---------------+-------+  
Retail         | UK             | 20
               | Japan          | 40
               | Germany        | 40
               | America        | 50

我需要拥有行业类别,且不能重复。做到这一点的最佳SQL命令是什么?

2 个答案:

答案 0 :(得分:3)

如果适合您,可以尝试以下方法。我还添加了SQL小提琴链接

http://sqlfiddle.com/#!4/d162a4/10

select (case when row_id=1 then industry else ' ' end) industry
        ,country
        ,price
from (select industry,country
            ,price
            ,row_number() over(partition by industry order by rownum) row_id
      from prices
     ) tmp

答案 1 :(得分:0)

您真的想在表示层中执行此操作。 SQL表和结果集表示无序集。唯一的例外是最终结果为order by时。因此,您需要非常小心以防重新排列。

您的数据似乎首先具有最低的价格。因此,在MySQL 8+或几乎所有其他数据库中,您可以执行以下操作:

select (case when row_number() over (partition by industry order by price, country) = 1
             then industry
        end) as industry,
       country, price
from t
order by industry, price, country;

我无法确定第二栏中的空格是否是故意的,但您可以包括它。

让我重复一遍:外部order by对于确保数据符合您的要求至关重要。没有结果,说“看起来”可能正确,但是下一次运行查询时,它可能不起作用。

在早期版本的MySQL中,您可以做同样的事情,但是看起来却有所不同。您尚未标记该版本,因此我假设使用的是最新版本。