Skip to content
Advertisement

SQL Server How to get number of unique values in a column and average score per values?

I have a table like this

and so on

What I ve done

I got distinct count for every city and avg metric value

But it is false

Appreciate any help

updated

There is also an additional column id in varchar format

Advertisement

Answer

The answer here depends on this assumption:

You always have exactly 3 metrics per ‘group’ (i.e. likes, dislikes and comments)

If that assumption is correct, the following will output what you are looking for:

Output:

How does this work?

By grouping on the city, we combine results for each city individually.

The count of metric_name gives the total metrics for that city (which is 6 in the case of your example). I divide this by 3 to give the unique count (based on the assumption I stated).

The average_metric_score calculation if the total of the metric_value for each city divided by the number of metrics (so 18 / 6 for Berlin). The reason for the CAST to FLOAT is to allow for a floating point answer. You could also use CONVERT if you prefer this to CAST.

Edit following OP update to question

OP edited the question to indicate that there is an ID column that allows the detection of metric grouping. This is an update to use that rather than assuming there are always 3 metrics per group.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement