在 Postgresql 中使用聚合和汇总
我有一个简单的查询,旨在根据其他列的 GROUP BY
聚合来汇总 total_miles
:
SELECT
tiermetric AS tier,
st AS state,
validation,
'All' AS study_type,
SUM(total_miles) as total_miles
FROM mu_schema.my_table
WHERE validation = 'VALID'
AND st = 'VA'
GROUP BY
tiermetric,
state,
validation,
study_type
ORDER BY tiermetric
目前,它输出:
tier state validation study_type total_miles
TIER 2 VA VALID All 335.005721465211
TIER 2 VA VALID All 0.337142821958635
TIER 3 VA VALID All 13.3444415576409
TIER 3 VA VALID All 1651.56942736755
TIER 4 VA VALID All 6606.44868771768
TIER 4 VA VALID All 1399.72188798074
我希望它输出:
tier state validation study_type total_miles
TIER 2 VA VALID All 335.3421
TIER 3 VA VALID All 1664.9138
TIER 4 VA VALID All 8006.1704
我在做什么这里错了?我基本上只想按等级汇总里程。
I have a simple query that is designed to summarize total_miles
based on a GROUP BY
aggregation of other columns:
SELECT
tiermetric AS tier,
st AS state,
validation,
'All' AS study_type,
SUM(total_miles) as total_miles
FROM mu_schema.my_table
WHERE validation = 'VALID'
AND st = 'VA'
GROUP BY
tiermetric,
state,
validation,
study_type
ORDER BY tiermetric
Currently, it outputs:
tier state validation study_type total_miles
TIER 2 VA VALID All 335.005721465211
TIER 2 VA VALID All 0.337142821958635
TIER 3 VA VALID All 13.3444415576409
TIER 3 VA VALID All 1651.56942736755
TIER 4 VA VALID All 6606.44868771768
TIER 4 VA VALID All 1399.72188798074
I want it to output:
tier state validation study_type total_miles
TIER 2 VA VALID All 335.3421
TIER 3 VA VALID All 1664.9138
TIER 4 VA VALID All 8006.1704
What am I doing wrong here? I basically want the miles summarized on tier only.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您按
study_type
进行分组,该列是基础表中每个层都有两个不同值的列。不过,您没有选择该列,而是使用常量“全部”。因此,您只需从GROUP BY
子句中删除study_type
列即可正常工作。You're grouping by
study_type
, which is a column that has two distinct values per each tier in your underlying table. You're not selecting that column though, you use a constant 'All' as that. So you simply have to remove thestudy_type
column from yourGROUP BY
clause and it'll work just fine.