0

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.

2 Answers 2

1

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 the study_type column from your GROUP BY clause and it'll work just fine.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes; that was the case! It works now, thanks.
0
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

1 Comment

See "Explaining entirely code-based answers". While this might be technically correct, it doesn't explain why it solves the problem or should be the selected answer. We should educate along with helping solve the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.