Sum of calculated field
Asked Answered
B

2

5

I have two tables:

  • table1 (a,b,c)
  • table2 (a,d,f)

I want to get for each b to get sum of multiplication of corresponding d and f

table 1 data

a   b      c
-------------
1   hello  3
2   bye    4

table 2 data

a  d  f
--------
1  5  3
1  2  4
2  1  3
2  2  3

result: hello:5*3+2*4 , bye:1*3+2*3
My query is:

  SELECT t1.a, 
         t2.d * t2.f AS m, 
         SUM(m)   
    FROM table1 AS t1, 
         table2 AS t2 
   WHERE t1.a = t2.a 
GROUP BY t1.b

So what is wrong here? In mysql I get #1054 - Unknown column 'm' in 'field list'

Burmese answered 23/5, 2011 at 22:27 Comment(2)
you can't use alias you've soon created. You need to repeat your formula.Schulte
what do you mean by repeating the formulaBurmese
P
5

Try:

SELECT t1.a, t2.d*t2.f AS m, SUM(t2.d*t2.f)
FROM table1 AS t1, table2 AS t2 
WHERE t1.a=t2.a GROUP BY t1.b

(I.e. expand the alias)

Parisian answered 23/5, 2011 at 22:34 Comment(0)
M
5

You can't refer to a column alias in the same SELECT clause - you either need to reproduce the formula:

  SELECT t1.a, 
         t2.d * t2.f AS m, 
         SUM(t2.d * t2.f)   
    FROM table1 AS t1 
    JOIN table2 AS t2 ON t1.a = t2.a 
GROUP BY t1.b

..or use a derived table/inline view:

SELECT x.a,
       x.m, 
       SUM(x.m)
  FROM (SELECT t1.a, 
               t2.d * t2.f AS m
          FROM table1 AS t1 
          JOIN table2 AS t2 ON t1.a = t2.a 
      GROUP BY t1.b) x

The earliest MySQL allows referring to column aliases is the GROUP BY clause (HAVING and ORDER BY also support column aliases). But most other databases only support as early as the ORDER BY clause.

Marimaria answered 23/5, 2011 at 22:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.