Sql 从两个字段中选择不同的行
我有一张有数百万条记录的表格 所以我可能有这些专栏 a、 b、c、d 我需要根据a列和b列选择所有不同的记录 但我需要选择a、b、c和d列,而不仅仅是a和b列 我能做这个吗 编辑 数据可能是 1,1,青蛙,绿色 1,1,青蛙,棕色 2,1,猫,黑色 2,4,狗,白色 所以我需要 1,1,青蛙,绿色 2,1,猫,黑色 2,4,狗,白色Sql 从两个字段中选择不同的行,sql,sql-server,Sql,Sql Server,我有一张有数百万条记录的表格 所以我可能有这些专栏 a、 b、c、d 我需要根据a列和b列选择所有不同的记录 但我需要选择a、b、c和d列,而不仅仅是a和b列 我能做这个吗 编辑 数据可能是 1,1,青蛙,绿色 1,1,青蛙,棕色 2,1,猫,黑色 2,4,狗,白色 所以我需要 1,1,青蛙,绿色 2,1,猫,黑色 2,4,狗,白色 SQL Server支持公共表表达式和窗口函数。下面的查询使用ROW\u NUMBER()根据组对记录进行排序。它按c ASC、d ASC进行排序(只需使用它)
SQL Server支持公共表表达式和窗口函数。下面的查询使用
ROW\u NUMBER()
根据组对记录进行排序。它按c ASC、d ASC进行排序(只需使用它)
- 你的人是谁
SELECT a, b, c, d FROM (
SELECT a, b, c, d, ROW_NUMBER() OVER (PARTITION BY a, b ORDER BY a, b) rn
FROM table
) sq
where rn = 1
请尝试:
select *
From(
select
row_number() over (partition by a, b order by a, b) RNum,
*
from
YourTable
)x
where RNum=1
样品
select * From(
select row_number() over (partition by a, b order by a, b) RNum, *
from(
select 1 a, 1 b, 'frog' c, 'green' d union all
select 1 a, 1 b, 'frog' c, 'brown' d union all
select 2 a, 1 b, 'cat' c, 'black' d union all
select 2 a, 4 b, 'dog' c, 'white' d)x
)y
where RNum=1
你能提供样品记录和你想要的结果吗?至少10条记录正好可以解释为什么第一行是
1,1,青蛙,绿色
而不是1,1,青蛙,棕色
?PS:不,DBMS中没有“自然”顺序,也没有内置的“第一个”condition@zerkms有关系吗?数据就是数据,我无法更改它。我只需要第一条记录,其中a列和b列构成唯一的pair@griegs:这很重要。而且,不,没有“第一”。您能为“第一”行提供任何技术(sql)标准吗?您使用的是什么rdbms?sqlserver?mysql?等等……我认为这是可行的。我会再测试一些,让你知道。非常感谢。
select * From(
select row_number() over (partition by a, b order by a, b) RNum, *
from(
select 1 a, 1 b, 'frog' c, 'green' d union all
select 1 a, 1 b, 'frog' c, 'brown' d union all
select 2 a, 1 b, 'cat' c, 'black' d union all
select 2 a, 4 b, 'dog' c, 'white' d)x
)y
where RNum=1