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
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
This uses SUM and GROUP BY. Make sure you use all the columns from the select in the GROUP BY to avoid undesired results.
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.
Try using sum()
function over group by
and colease
. Plenty of examples in google.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.