SQL distinct for 2 fields in a database

SqlDistinct

Sql Problem Overview


Can you get the distinct combination of 2 different fields in a database table? if so, can you provide the SQL example.

Sql Solutions


Solution 1 - Sql

How about simply:

select distinct c1, c2 from t

or

select c1, c2, count(*)
from t
group by c1, c2

Solution 2 - Sql

If you want distinct values from only two fields, plus return other fields with them, then the other fields must have some kind of aggregation on them (sum, min, max, etc.), and the two columns you want distinct must appear in the group by clause. Otherwise, it's just as Decker says.

Solution 3 - Sql

You can get result distinct by two columns use below SQL:

SELECT COUNT(*) FROM (SELECT DISTINCT c1, c2 FROM [TableEntity]) TE

Solution 4 - Sql

If you still want to group only by one column (as I wanted) you can nest the query:

select c1, count(*) from (select distinct c1, c2 from t) group by c1

Solution 5 - Sql

Share my stupid thought:

Maybe I can select distinct only on c1 but not on c2, so the syntax may be select ([distinct] col)+ where distinct is a qualifier for each column.

But after thought, I find that distinct on only one column is nonsense. Take the following relationship:

   | A | B
__________
  1| 1 | 2
  2| 1 | 1

If we select (distinct A), B, then what is the proper B for A = 1?

Thus, distinct is a qualifier for a statement.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionleoraView Question on Stackoverflow
Solution 1 - SqlHoward PinsleyView Answer on Stackoverflow
Solution 2 - SqlJeffrey L WhitledgeView Answer on Stackoverflow
Solution 3 - SqlWilson WuView Answer on Stackoverflow
Solution 4 - SqlDennoView Answer on Stackoverflow
Solution 5 - SqlyoukaichaoView Answer on Stackoverflow