Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate arithmetic expression of column members database table?

I have result from this query

SELECT
    myTable.Branch AS Branch,
    myTable.Quarter AS Quarter,
    SUM(myTable.Sales) AS Sales
FROM
    myTable
GROUP BY
    myTable.Branch,
    myTable.Quarter

Branch  Quarter Sales
B1      Q1      17
B1      Q2      7
B1      Q3      1
B1      Q4      8
B1      Q5      12
B2      Q1      8
B2      Q2      5
B2      Q3      2
B2      Q4      14
B2      Q5      17

Now I want to get calculate member lets say Q1-Q3 then result should look like

Branch  Quarter     Sales
B1      Q1          17
B1      Q2          7
B1      Q3          1
B1      Q4          8
B1      Q5          12
B1      Q1-Q3       16
B2      Q1          8
B2      Q2          5
B2      Q3          2
B2      Q4          14
B2      Q5          17
B2      Q1-Q3       6

Expression can be any valid arithmetic expression like (Q1+Q2-Q3)*2

like image 779
Anurag Tripathi Avatar asked Dec 24 '13 09:12

Anurag Tripathi


1 Answers

You can create a table that has Q1, Q2, Q3, Q4 as columns for each branch:

http://sqlfiddle.com/#!6/eca51/14/0

SELECT
    Branch,
    SUM(CASE WHEN quarter='Q1' THEN sales END) AS Q1,
    SUM(CASE WHEN quarter='Q2' THEN sales END) AS Q2,
    SUM(CASE WHEN quarter='Q3' THEN sales END) AS Q3,
    SUM(CASE WHEN quarter='Q4' THEN sales END) AS Q4
FROM
    sales
GROUP BY Branch

This gives:

| BRANCH | Q1 | Q2 | Q3 | Q4 |
|--------|----|----|----|----|
|     B1 | 17 |  7 |  1 |  8 |
|     B2 |  8 |  5 |  2 | 13 |

You can use that as a sub-query and perform any arithmetic you like.

SELECT Branch, Q1+2*Q2 AS Weighted,SQRT(Q1*Q2) GeometricMean
  FROM (
  SELECT
      Branch,
      SUM(CASE WHEN quarter='Q1' THEN sales END) AS Q1,
      SUM(CASE WHEN quarter='Q2' THEN sales END) AS Q2,
      SUM(CASE WHEN quarter='Q3' THEN sales END) AS Q3,
      SUM(CASE WHEN quarter='Q4' THEN sales END) AS Q4
  FROM
      sales
 GROUP BY Branch) AS BQ

This gives:

| BRANCH | WEIGHTED |   GEOMETRICMEAN |
|--------|----------|-----------------|
|     B1 |       31 | 10.908712114636 |
|     B2 |       18 |  6.324555320337 |

This relies on the number of quarters being known and fixed - I'd have guessed there were 4 but you seem to have 5.

like image 89
SQL Hacks Avatar answered Nov 13 '22 00:11

SQL Hacks