I have few columns in a table
Col1, Col2, Col3, Col4
Now I want to select like this
SELECT DISTINCT (Col1, Col2, Col3), Col4
i.e. get the distinct based on only these three colunms.
I have few columns in a table
Col1, Col2, Col3, Col4
Now I want to select like this
SELECT DISTINCT (Col1, Col2, Col3), Col4
i.e. get the distinct based on only these three colunms.
Just GROUP BY Col1, Col2, Col3
with an aggregate function with the col4
like MAX
, MIN
, etc .. like so:
SELECT Col1, Col2, Col3, MAX(Col4)
FROM TableName
GROUP BY Col1, Col2, Col3
From a comment to another answer:
Can I get like this Col1, Col2 , Col3 and (Col4 in delimiter form)
Yes, you can use the for xml path
.
select Col1,
Col2,
Col3,
(
select ',' + T2.Col4
from YourTable T2
where T1.Col1 = T2.Col1 and
T1.Col2 = T2.Col2 and
T1.Col3 = T2.Col3
for xml path(''), type
).value('substring((./text())[1], 2)', 'varchar(max)') as Col4
from YourTable as T1
group by T1.Col1, T1.Col2, T1.Col3
The group by and distinct perform almost similar functionality in SQL:
SO both queries below are almost equivalent:
SELECT DISTINCT Col1, Col2, Col3 FROM tbl
SELECT Col1, Col2, Col3 FROM tbl GROUP BY Col1, Col2, Col3
select distinct ( Convert(varchar(255),Col1) +' '+
Convert(varchar(255),Col2)+' '+Convert(varchar(255),Col3)),
Col4 from clients