Skip to content
Advertisement

How to summarize multiple fields in sql

How can I

V1,V2,V4,V5 already summarized data as v1,v2,v3,v4. How can I sum v1+v2 and v4+v5 and GTOT

I Used this code for summarized for v1,v2,v3,v4 as below

How can I get the sum of v1+v2 and v4+v5 GTOT(v1+v4 and v2+v5) for these columns any idea about this.

Advertisement

Answer

Probably the simplest method is to use a subquery or CTE:

Notes:

  • MySQL has a handle method of counting the results of boolean expressions, using sum() with the boolean expression. In a numeric context, true is 1 and false is 0.
  • Only use single quotes for string and date constants; never use them for column names. That will just lead to hard-to-debug errors, because of the confusion between a string and column name.
  • You don’t need the subquery; you can repeat the logic using, say: sum(car in ('Red', 'Blue') and ver = 'HIGH') as v1_2. Such logic can become harder to maintain.
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement