Getting a column when output during grouping, but without grouping this column only if there is only one row for the grouped column

Table1

t1Id t1Name 


Table2

 t2Id t2Name 

Table1_Table2_Mapping

 t1Id t2Id 

In this query below, as the second column in the output, I need the t2Name column, where Having COUNT(t1Id) = 1 , and I want some fixed value ('Common'), where Having COUNT(t1Id) > 1

 Select t1Id from Table1_Table2_Mapping Group By t1Id 

Thanks in advance.

+4
source share
1 answer
 SELECT m.t1Id, CASE WHEN COUNT(*) = 1 THEN MAX(t2.t2Name) ELSE 'Common' END FROM Table1_Table2_Mapping m JOIN Table2 t2 ON t2.t2Id = m.t2Id GROUP BY m.t1Id 
+6
source

Source: https://habr.com/ru/post/1390610/


All Articles