Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- `--AVG used only in Select correctly does the average calculation from the detail (child) table SELECT sd.customer, AVG(score) AS avg_score_group from score_detail as sd
- JOIN score_master as sm ON sd.customer = sm.customer
- GROUP BY sd.customer
- --Using AVG to actually update the master table with averages from child
- table has incorrect calculations for some grouped records
- UPDATE score_master
- SET avg_score = t.avg_score_group
- FROM (
- SELECT AVG(score) AS avg_score_group from score_detail as sd
- JOIN
- score_master as sm
- ON
- sd.customer = sm.customer
- GROUP BY sd.customer
- ) AS t
- --Let us explore master table
- SELECT * FROM score_master;
- --Table structures:
- CREATE TABLE [dbo].[score_detail](
- [customer] [float] NULL,
- [score] [float] NULL
- ) ON [PRIMARY]
- CREATE TABLE [dbo].[score_master](
- [customer] [float] NULL,
- [avg_score] [float] NULL
- ) ON [PRIMARY]
- -- Data to calculate average has 17 Decimal points:
- INSERT [dbo].[score_detail] ([customer], [score]) VALUES (2, -0.07216878364870323)`
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement