Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to divide two values from the same column in SQL

As the title states I would like to divide two values with each other that are in the same column. E.g.

    A             B              C            D
  Shirts         2011           85            0
  Shirts         2012           92      percent change from 2011 to 2012
  Shirts         2013          100      percent change from 2012 to 2013
  Pants          2011           31            0
  Pants          2012           42      percent change from 2011 to 2012
  Pants          2013           55      percent change from 2012 to 2013
  Jacket         2011           10            0
  Jacket         2012           16      percent change from 2011 to 2012
  Jacket         2013           18      percent change from 2012 to 2013

In this example column D would be a derived from column C, where the value of 2012 is subtracted from 2011, and then times by a 100 to get the percent.

I don't know how to set the query up I tried doing a bunch of sub-queries but didn't know how to link them together. Any help would be greatly appreciated.

like image 341
user2167857 Avatar asked Mar 14 '13 03:03

user2167857


1 Answers

Here's an option to get what you're after

SELECT t1.a, t1.b, t1.c,
    CASE WHEN t2.c IS NULL THEN 0 ELSE t1.c - t2.c END AS d,
    CASE WHEN t2.c IS NULL THEN 0 ELSE (1.0 * t1.c - t2.c) / t1.c * 100.0 END AS pct
FROM t t1
LEFT OUTER JOIN t t2 ON t1.a = t2.a
    AND t1.b = t2.b + 1

SQL Fiddle Example

like image 159
bobs Avatar answered Oct 07 '22 22:10

bobs