If I understood your question correctly, you want distinct ref
number with doc
number is the following condition (as per the output shown).
If the all the existing doc
numbers are same for a ref
number, then get max(doc)
otherwise sum(doc)
.
SELECT ref,
(CASE WHEN MAX(doc) = MIN(doc) THEN MAX(doc) ELSE SUM(doc) END) AS doc
FROM table1
GROUP BY ref
solved SELECT statement with if ELSE in SQL Server