SQL获取唯一记录并维护订单

时间:2019-05-07 08:32:41

标签: sql sql-server group-by sql-order-by distinct

我的桌子上有下面的记录。

enter image description here

我想要不同的记录,当我按组分组时,它会失去顺序。我要维持秩序。我想要如下结果:

enter image description here

这是我的查询

select route_id,fixcode,fixdescription 
from route_fixcodes 
group by route_id,fixcode,fixdescription 
having route_id = 995063

4 个答案:

答案 0 :(得分:0)

尝试以下代码。我想这就是您要寻找的

CREATE TABLE [dbo].[route_fixcodes](
    [route_id] [INT] NULL,
    [fixcode] [INT] NULL,
    [fixdescription] [NVARCHAR](50) NULL
) ON [PRIMARY]

GO

INSERT INTO [route_fixcodes]
([route_id] ,[fixcode],[fixdescription])
VALUES
(995063,100,'Issue Observed'),
(995063,137,'Swap Altice One Pack'),
(995063,249,'Defective CPE Equip.'),
(995063,112,'Outside coax repair'),
(995063,258,'Preventative Maint'),
(995063,100,'Issue Observed'),
(995063,137,'Swap Altice One Pack'),
(995063,249,'Defective CPE Equip.'),
(995063,112,'Outside coax repair'),
(995063,258,'Preventative Maint'),
(995063,100,'Issue Observed'),
(995063,137,'Swap Altice One Pack'),
(995063,249,'Defective CPE Equip.'),
(995063,112,'Outside coax repair'),
(995063,258,'Preventative Maint')
GO


SELECT * INTO #route_seq FROM dbo.route_fixcodes


ALTER TABLE #route_seq ADD seq  [INT] IDENTITY(1,1)

SELECT MIN(seq) AS newseq,  route_id,fixcode,fixdescription 
FROM #route_seq
group by route_id,fixcode,fixdescription 
ORDER BY MIN(seq)

答案 1 :(得分:0)

SQL表表示无序集。没有排序,除非有列指定排序。

让我假设有一个。 。 。我将其称为id。然后,您可以执行以下操作:

select route_id, fixcode, fixdescription 
from route_fixcodes 
where route_id = 995063
group by route_id, fixcode, fixdescription 
order by min(id);

请注意,我已将having子句更改为where子句。通常,这将减少聚合的数据量-这对性能非常有利。

如果没有排序列,但特别希望结果以100、137、249、112、258的顺序排列,则可以使用case表达式或类似的逻辑:

select route_id, fixcode, fixdescription 
from route_fixcodes 
where route_id = 995063
group by route_id, fixcode, fixdescription 
order by charindex(id, '100,137,249,112,258');

(这只是一个方便的简写,并非在所有情况下都适用,但适用于您提供的数据。)

答案 2 :(得分:0)

以下查询给了我我想要的解决方案。

从route_fixcodes中选择最小的route_id,fixcode,fixdescription,MIN(id),其中route_id = @RouteId GROUP BY route_id,fixcode,fixdescription按minip排序

答案 3 :(得分:-1)

只需添加不同的内容:

select distinct route_id,fixcode,fixdescription 
from route_fixcodes 
group by route_id,fixcode,fixdescription 
having route_id = 995063
相关问题