【发布时间】:2021-12-23 09:25:12
【问题描述】:
我在 SQL Server 2017 中工作,我有以下两个表:
create table Computer (
Id int Identity(1, 1) not null,
Name varchar(100) not null,
constraint pk_computer primary key (Id)
);
create table HardDisk (
Id int Identity(1, 1) not null,
Interface varchar(100) not null,
ComputerId int not null,
constraint pk_harddisk primary key (Id),
constraint fk_computer_harddisk foreign key (ComputerId) references Computer(Id)
);
我有如下数据:
查询
我当前的查询如下:
-- select query
select c.Id as computer_id,
string_agg(cast(hd.Interface as nvarchar(max)), ' ') as hard_disk_interfaces
from Computer c
left join HardDisk hd on c.Id = hd.ComputerId
group by c.Id;
这让我得到以下信息:
computer_id | hard_disk_interfaces
-------------+----------------------
1 | SATA SAS
2 | SATA SAS SAS SAS SATA
但是,我只想要不同的值,我想最终得到:
computer_id | hard_disk_interfaces
-------------+----------------------
1 | SATA SAS
2 | SATA SAS
我尝试将distinct 放在string_agg 前面,但是没有用。
关键字“distinct”附近的语法不正确。
【问题讨论】:
-
这能回答你的问题吗? Produce DISTINCT values in STRING_AGG
-
我都看到了,但并不真正了解如何应用它们。 ??????
标签: sql sql-server