1

I have the columns and rows for the table A,

tableid featureid col3 col4 coldatetime
1 1 AD 4 2022-06-22 09:00:00
2 2 BC 5 2022-06-22 09:00:00
3 1 AE 6 2022-06-22 10:00:00
4 3 BD 7 2022-06-22 11:00:00
5 2 BB 8 2022-06-22 16:00:00

I need the following result in the SQL Server,

featureid col3 col4
1 AD 4,6
2 BC 5,8
3 BD 7

If I run the following query:

select featureid,
       STRING_AGG(col3,',') as col3,
       STRING_AGG(col4,',') as col4 
from table_server 
group by feature_id;

I am getting the following result,

featureid col3 col4
1 AD,AE 4,6
2 BC,BD 5,8
3 BD 7

How Should I change my query to get the Col3 to have only one record?

I have this clarification, whether this is possible or not?

I have zero knowledge with SQL Server, can anyone help me?

Charlieface
  • 52,284
  • 6
  • 19
  • 43
  • So why do you use STRING_AGG for col3 knowing that you only want a single value? Maybe just change that to MIN for col3? – SMor Jun 26 '22 at 14:57

1 Answers1

1

Seems like you need MIN instead of STRING_AGG

select
  s.featureid,
  MIN(s.col3, ',') as col3,
  STRING_AGG(s.col4, ',') as col4 
from table_server s
group by
  s.feature_id;
Charlieface
  • 52,284
  • 6
  • 19
  • 43