简体   繁体   中英

How to join the same table and calculate data in SQL alchemy

I have a table looks like this:

| id | company_name | income | year |
|----|--------------|--------|------|
| 0  | A            | 10     | 2010 |
| 1  | A            | 20     | 2011 |
| 2  | A            | 30     | 2012 |
| 3  | B            | 20     | 2010 |
| 4  | B            | 15     | 2011 |

I want to get a table of A like this:

|                | 2010 | 2011 | 2012 |
|----------------|------|------|------|
| income         | 10   | 20   | 30   |
| increase_ratio | -    | 2    | 1.5  |

In SQL I can get this kind of result by using alias and join, but how can I get this using python SQL alchemy ?

The database of the table is MySQL , schema of the original table looks like :

from sqlalchemy import MetaData, Integer, Float, String
from sqlalchemy import Table, Column

metadata = MetaData()

income = Table(
    'income', metadata,
    Column('company_id', Integer, primary_key=True),
    Column('company_name', String(255), nullable=False),
    Column('income', Float, nullable=False),
    Column('year', Integer, nullable=False),
)

Try this:

select 'Income' AS ` `, MAX(CASE WHEN Year= 2010 THEN income END)`2010`
  ,MAX(CASE WHEN Year= 2011 THEN income END)`2011`
  ,MAX(CASE WHEN Year= 2012 THEN income END)`2012`
from(
  SELECT A.*,(A.income/B.income)increase_ratio
  FROM My_Table A
  LEFT JOIN My_Table B ON B.id = A.id-1
  WHERE A.company_name = 'A'
  )D
 UNION
 select 'increase_ratio' AS ` `,MAX(CASE WHEN Year= 2010 THEN increase_ratio END)`2010`
  ,MAX(CASE WHEN Year= 2011 THEN increase_ratio END)`2011`
  ,MAX(CASE WHEN Year= 2012 THEN increase_ratio END)`2012`
from(
  SELECT A.*,(A.income/B.income)increase_ratio
  FROM My_Table A
  LEFT JOIN My_Table B ON B.id = A.id-1
  WHERE A.company_name = 'A'
  )D

Check this in the #SQL Fiddle

Output:

                2010    2011    2012
Income          10      20      30
increase_ratio  (null)  2      1.5

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM