-1

I have the following table t

id   a   b    c
1    1   1    1
2    2   1    1

and the table t1

id  a   b   c  p
1  1    1   1   47 
2  1    1   1   2
3  2    1   1   78

My purpose is to get a table

    id   a   b    c  p 
    1    1   1    1  49
    2    2   1    1  78

I tried the following script but it not works @y=@y+t1.p is always null :

select t.id,t1.a, t1.b , t1.c ,@y=@y+t1.p from t1
inner join t
where t.a=t1.a
and t.b=t1.b
and t.c=t1.c

For more details enter link description here

4 Answers 4

2

This gives the result you want:

select t.id,
       t1.a, 
       t1.b , 
       t1.c ,
       SUM(t1.p) from t1
inner join t ON t.a=t1.a and t.b=t1.b and t.c=t1.c
group by t.id, t1.a, t1.b, t1.c

sqlfiddle demo

This uses SUM and GROUP BY. Make sure you use all the columns from the select in the GROUP BY to avoid undesired results.

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

1 Comment

That's right: the group by has been properly used. However, there could be a small improvement in terms of performance. Assuming the ONLY_FULL_GROUP_BY sql mode is not set (which is the default) and assuming t.id functionally identifies all the the other fields in the t table then the group by could only be performed by t.id
1

Try using sum() function over group by and colease. Plenty of examples in google.

One link is here

Comments

1

The calculation part needs to be done this way (if you need it sometime again)

SET @y = 0;

select t.id,t1.a, t1.b , t1.c ,(@y:=@y + t1.p) from t1
inner join t
where t.a=t1.a
and t.b=t1.b
and t.c=t1.c
;

see demo http://www.sqlfiddle.com/#!2/68a61/8

Comments

1

You need to add the GROUP BY statement and use SUM

SELECT
  t.id,
  t1.a, 
  t1.b, 
  t1.c,
  SUM(t1.p) AS p
FROM 
  t1
  INNER JOIN t
     USING (a, b, c)
GROUP BY a, b, c

You can see it running here. It is possible to do it with variables but type of problem is usually solved with aggregate functions.

2 Comments

Note t.id is be random value now (your lucky its correct now).. I think you should read this dbasquare.com/2012/05/15/… and an demo with sql_mode -> sqlfiddle.com/#!2/68a61/14.. check Filipe Silva's answer how it should be done..
Table t and t1 are linked with one to many relation, by using id from table t problem descibed in the dbsquare post will never occur and ONLY_FULL_GROUP_BY is turned off by default.

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.