is there a way to group by and still show other variables without infringing no-aggregate clause

Ivan G :

Table:

id | value
---+-----------
 1 | Monday 
 2 | Tuesday 
 3 | Tuesday 
 4 | Wednesday

I need it to display like:

value     | count | id1 | id2 
----------+-------+-----+-----
Monday    |  1    |  1  |
Tuesday   |  2    |  2  |  3 
Wednesday |  1    |  4  |

But using the Group By function will not work for obvious reasons ("id" is not contained in either the aggregate function or the GROUP BY clause).

However, I still need this done and I have exhausted my knowledge of juggling the variables into temp tables. Need this on SSMS, Any help is appreciated, thank you.

Gordon Linoff :

You just want string aggregation. Here is a typical method:

select value, count(*), string_agg(id, ',') as ids
from t
group by value;

If you want the values in two columns, you can use MIN() and MAX():

select value, count(*),
       min(id) as id1, coalesce(max(id), min(id)) as id2
from t
group by value;

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=398436&siteId=1