我有一个这样的表:
Source table "tab"
column1 column2
x 1
x 2
y 1
y 2
y 3
z 3
如何构建查询以分别在两列的每一列中获取具有唯一值的结果。例如,我想得到如下一组结果:
column1 column2
x 1
y 2
z 3
或
column1 column2
x 2
y 1
z 3
或者...
谢谢。
最佳答案
你要求的东西很难,因为它很奇怪:SQL 将行视为相关字段,但你要求制作两个单独的列表(来自 col1 的不同值和来自 col2 的不同值)然后将它们显示在一个输出表中而不是关心行如何匹配。
您可以通过按照这些行编写 SQL 来做到这一点。为每一列写一个单独的 select distinct,然后以某种方式将它们放在一起。我会通过给每个结果中的每一行一个行号,然后将它们加入一个大的数字列表来将它们放在一起。
不清楚您希望 null 表示什么意思。这是否意味着其中一列中有一个空值,或者每列中的不同值的数量不同?这个问题来自于要求与典型的关系逻辑不匹配的东西。
这是一个示例,从数据中删除 null
值,因为这会混淆问题,使用不同的数据值以避免将 rowNumber 与数据混淆,因此一列中有 3 个不同的值,另一列中有 4 个不同的值.这适用于 SQL Server,大概有一个适用于 PostgreSQL 的变体。
if object_id('mytable') is not null drop table mytable;
create table mytable ( col1 nvarchar(10) null, col2 nvarchar(10) null)
insert into mytable
select 'x', 'a'
union all select 'x', 'b'
union all select 'y', 'c'
union all select 'y', 'b'
union all select 'y', 'd'
union all select 'z', 'a'
select c1.col1, c2.col2
from
-- derived table giving distinct values of col1 and a rownumber column
( select col1
, row_number() over (order by col1) as rowNumber
from ( select distinct col1 from mytable ) x ) as c1
full outer join
-- derived table giving distinct values of col2 and a rownumber column
( select col2
, row_number() over (order by col2) as rowNumber
from ( select distinct col2 from mytable ) x ) as c2
on c1.rowNumber = c2.rowNumber
关于PostgreSQL - 如何分别区分两列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22112890/