I am working in SQL Server 2017 and I have the following two tables:
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)
);
I have data such as:
Query
My current query is the following:
-- 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;
This gets me the following:
computer_id | hard_disk_interfaces
-------------+----------------------
1 | SATA SAS
2 | SATA SAS SAS SAS SATA
However, I only want the distinct values, I'd like to end up with:
computer_id | hard_disk_interfaces
-------------+----------------------
1 | SATA SAS
2 | SATA SAS
I tried to put distinct
in front of the string_agg
, but that didn't work.
Incorrect syntax near the keyword 'distinct'.