SQL Query to get the difference from average for every row with grouping

20 pts.
Tags:
Microsoft Access
SQL
SQL Query
SQLite
Hi there, i was wondering if anyone would be kind enough to help with something i am struggling with... I have a table something like this: Region ID Cost s1 1 v1
 s1 2 v2
 s1 3 v3
s2 4 v4
s2 5 v5
s2 6 v6
What I am trying to achieve is to get a result set that looks like this using a single query
Cost Difference from mean
ID Difference from mean in region
1 sum(v1, v2, v3) - v1
2 sum(v1, v2, v3) - v2
3 sum(v1, v2, v3) - v3
4 sum(v4, v5, v6) - v4
5 sum(v4, v5, v6) - v5
6 sum(v4, v5, v6) - v6
Any advice much appreciated! thanks v much


Software/Hardware used:
SQL, SQlite, Access/JET

Answer Wiki

Thanks. We'll let you know when a new response is added.

You could use an in-line view, but I’m not sure if this is supported on SQlite.

Something like this:

<pre>SELECT y.region, y.id, m.mean-y.cost AS dif_from_mean
FROM your_table y
JOIN
(SELECT region, AVG(cost) mean
FROM your_table
GROUP BY region) m
ON y.region = m.region;</pre>

Discuss This Question: 4  Replies

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when members answer or reply to this question.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
  • 150
    what (#) mean in sql query

    30 pointsBadges:
    report
  • 150
    what # mean in sql query
    30 pointsBadges:
    report
  • 150
    My internet explorer displays 'browser sittings change' please i want the solution
    30 pointsBadges:
    report
  • msi77
    Try this:--------select id, (select avg(cost) from table T1 where T1.region=T2.region) - cost as "Difference from mean in region"from table T2--------
    1,670 pointsBadges:
    report

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

To follow this tag...

There was an error processing your information. Please try again later.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Thanks! We'll email you when relevant content is added and updated.

Following