我有这样的桌子
city metric_name metric_value id
Berlin likes 1 1a
Berlin dislikes 2 1a
Berlin comments 3 1a
Berlin likes 4 1b
Berlin dislikes 5 1b
Berlin comments 3 1b
Hamburg likes 1 1c
Hamburg dislikes 2 1c
Hamburg comments 3 1c
Hamburg likes 2 1d
Hamburg dislikes 4 1d
Hamburg comments 5 1d
等等
My ideal result is this
city city_count_unique average_metric_score
Berlin 2 3 (sum metric_value / sum metric_names)
Hamburg 2 2,8
我做了什么
我得到了每个城市的不同计数和平均指标值
SELECT AVG(T.metric_value), T.city,
COUNT(*) AS 'city_count_unique'
FROM
(SELECT DISTINCT metric_value, city
FROM dbo.Table) as T
GROUP BY T.city
但这是错误的
感谢任何帮助
更新 还有一个varchar格式的附加列ID
OP编辑了该问题,以表明存在一个ID列,该列允许检测度量标准分组。这是使用此更新,而不是假设每个组始终有3个指标。
SELECT city,
COUNT(id) AS city_count_unique,
CAST(SUM(metric_value_total) AS FLOAT) / SUM(metric_value_count) AS average_metric_score
FROM (
SELECT city,
id,
SUM(metric_value) metric_value_total,
COUNT(metric_value) AS metric_value_count
FROM #Table
GROUP BY city, id
) a
GROUP BY city
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。