在 Postgresql 中使用聚合和汇总

Using Aggregation and Summarization in 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

我在这里做错了什么?我基本上只想按等级汇总里程。

您正在按 study_type 分组,这是一个列,在您的基础 table 中每个层都有两个不同的值。虽然您没有选择该列,但您使用常量 'All' 作为那个。因此,您只需从 GROUP BY 子句中删除 study_type 列,它就可以正常工作。

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
ORDER BY tiermetric