如何在SQL炼金术中加入同一个表并计算数据

时间:2018-04-19 09:56:31

标签: python mysql sql orm sqlalchemy

我的表格如下:

correlationId

我想得到一张像这样的A表:

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

在SQL中,我可以通过使用别名和连接获得此类结果,但是如何使用| | 2010 | 2011 | 2012 | |----------------|------|------|------| | income | 10 | 20 | 30 | | increase_ratio | - | 2 | 1.5 | 来获取此结果?

表的数据库是python SQL alchemy,原始表的模式如下:

MySQL

1 个答案:

答案 0 :(得分:1)

试试这个:

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