如何在sql炼金术中连接同一个表并计算数据

wnvonmuf  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(315)

我有一张这样的table:

| 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 |

我想要一张这样的table:

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

在sql中,我可以通过使用alias和join得到这种结果,但是如何使用alias和join得到这种结果呢 python SQL alchemy ?
表的数据库是 MySQL ,原始表的架构如下所示:

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),
)
u5i3ibmn

u5i3ibmn1#

试试这个:

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

在“sql fiddle”中检查这个
输出:

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

相关问题