如何从sql表中的单个列中选择不同的记录

时间:2014-11-15 05:18:46

标签: sql datatable distinct

我想从此sql表中的每一列中检索不同的行

我的表

1    Apple
2    Banana
3    Apple
2    Apple
1    Orange

我想要这样的结果:

1   Apple
2   Banana
3   Orange

请帮我解决这个问题

3 个答案:

答案 0 :(得分:1)

您可以通过以下方式获取不同的名称:

select distinct name
from table t;

您可以通过执行以下操作添加第一列:

select row_number() over (order by name) as id, name
from (select distinct name
      from table t
     ) t;

大多数数据库都支持ANSI标准行号。您尚未使用数据库对此进行标记,因此这是最常用的解决方案。

编辑:

哦,你想要两列各有值。我会将其视为full outer join

select nu.num, na.name
from (select num, row_number() over (order by num) as seqnum
      from table
      group by num
     ) nu full outer join
     (select name, row_number() over (order by name) as seqnum
      from table t
      group by name
     ) na
     on nu.seqnum = na.seqnum;

每个子查询枚举每列中的值。 full outer join确保即使在一边或另一边缺少值,也会有值。

答案 1 :(得分:0)

请尝试

select *,row=rank() over(order by name) from  (SELECT distinct name FROM abc) as cte 

with cte as
(
    SELECT distinct name FROM abc
) 
select *,row=rank() over(order by name) from cte 

输出

| row       | Name |
|-----------|----------|
|         1 |    Apple |
|         2 |   Banana |
|         3 |   Orange |

答案 2 :(得分:0)

概念证明。
在Oracle 11.2上测试

WITH
MyTable (firstName, lastName) AS (
  SELECT '1', 'Apple' FROM DUAL UNION ALL
  SELECT '2', 'Banana' FROM DUAL UNION ALL
  SELECT '3', 'Apple' FROM DUAL UNION ALL
  SELECT '2', 'Apple' FROM DUAL UNION ALL
  SELECT '4', 'Apple' FROM DUAL UNION ALL
  SELECT '1', 'Orange' FROM DUAL),
Ranked AS (
  SELECT DISTINCT
    firstName
    , DENSE_RANK() OVER (ORDER BY firstName) AS fnRnk
    , lastName
    , DENSE_RANK() OVER (ORDER BY lastName) AS lnRnk
  FROM MyTable  
)
SELECT
  DISTINCT R1.firstName, R2.lastName FROM Ranked R1 FULL OUTER JOIN Ranked R2 ON R1.fnRnk = R2.lnRnk ORDER BY lastName NULLS LAST, firstName
;

返回

| FIRSTNAME | LASTNAME |
|-----------|----------|
|         1 |    Apple |
|         2 |   Banana |
|         3 |   Orange |
|         4 |   (null) |

在原始数据中添加了一行,以演示不同长度的列。

SQL Fiddle