Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 在多个列上选择唯一的组合_Sql_Sql Server - Fatal编程技术网

Sql 在多个列上选择唯一的组合

Sql 在多个列上选择唯一的组合,sql,sql-server,Sql,Sql Server,我正在使用SQL Server 2012。我无法在多个列上选择distinct,并且权限有限 使用此示例数据 orderNum CustomerNum OrderDesc Structure ------- ---------- -------- -------- 001 456 repair House 002 456 paint House 003 678

我正在使用SQL Server 2012。我无法在多个列上选择distinct,并且权限有限

使用此示例数据

orderNum    CustomerNum OrderDesc   Structure
-------     ----------  --------    --------
001          456        repair      House
002          456        paint       House
003          678        repair      Fence
004          789        repair      House
005          789        paint       House
006          789        repair      Fence
007          789        paint       Fence
我想写一个查询来显示正在处理的每个独特结构,即CustomerNum和structure的每个独特组合。我不在乎一个建筑是在粉刷还是在修理,或者两者兼而有之

因此,我希望得到如下结果:

orderNum    CustomerNum OrderDesc   Structure
-------     ----------  --------    --------
001          456        repair      House
003          678        repair      Fence
004          789        repair      House
006          789        repair      Fence
请注意,CustomerNum 789出现了两个OrderNum,因为房屋和围栏都在处理中。但是,我不希望CustomerNum 789出现4次

我为实现这一目标所做的是 挑选* 从命令


然后粘贴到Excel并删除重复项,同时选中CustomerNum和Structure。但我相信,在没有Excel的情况下,一定有办法做到这一点。

您可以使用
行编号()


获取每个客户的最小订单号、最小订单描述、结构的简单方法

DECLARE@table表(orderNum char(3)、CustomerNum int、OrderDesc varchar(10)、结构varchar(10))
插入到@table值中
('004',789,'repair','House'),
('005',789,'paint','House'),
('006',789,'repair','Fence'),
(‘007’、‘789’、‘油漆’、‘栅栏’);
选择customernum、structure、min(ordernum)作为ordernum、min(OrderDesc)作为OrderDesc
来自@table
按客户分组UM,结构
客户号 结构 ordernum 订单描述 789 栅栏 006 油漆 789 房屋 004 油漆
根据问题指南,请说明您尝试了什么,并告诉我们您发现了什么(在本网站或其他地方),以及为什么它不能满足您的需要。使用CTE不需要任何特殊权限。我的实际数据从4658行开始,当我根据CustomerNum和结构在Excel中删除重复项时,我只剩下4478行。这是我期待的结果。使用此查询时,仅检索512行。我在这个查询中添加的唯一内容是对where子句添加一些更基本的过滤器。我相信如果我将最后一行改为:其中seqnum=1,column1='x'和column2,比如“%y%”@SeanM,它应该仍然有效。它应该会起作用。但是这些过滤器删除的行可能比您预期的多。
select t.*
from (select t.*,
             row_number() over (partition by customernum, structure order by ordernum) as seqnum
      from t
     ) t
where seqnum = 1;