Sql-server – select one row based on a string

querysql server

I have a table like this:
enter image description here

and I want to have the output like this:

enter image description here

If I use case to this, I'm not getting a unique value for each pc. I used:

case
when software like '%7zip%' then software
else 'no'
end;

and I'm getting for computer_id something like this:
enter image description here

I don't know what function to use and if I can do this with 'case'.
Thank you!

Best Answer

It's not entirely clear what you're trying to accomplish but I think you basically want only the Computer_ids of the rows that have Sofrware of 7Zip or the Computer_ids of the rows that don't have Software of 7Zip in any other row for that same Computer_id, and you want the value to be no. You can accomplish this with a UNION ALL clause and an outer self-join like so:

-- This gets you only the rows with 7Zip in the Software field
SELECT Computer_id, Software
FROM TableName
WHERE Software like '%7zip%'

UNION ALL

-- This gets you only the rows of Computer IDs who don't have Software containing 7Zip in any other row
SELECT T1.Computer_id, 'no' AS Software
FROM TableName T1
LEFT JOIN TableName T2
    ON T1.Computer_id = T2.Computer_id
    AND T2.Software like '%7zip%'
WHERE T1.Software NOT LIKE '%7Zip%' 
    AND T2.Computer_id IS NULL

If you have the same Computer_id more than once in either case and you only want one row for it, you can add the DISTINCT clause to your SELECT clause in each query of the UNION ALL above too.