在另一个字段上使用groupby将行值区分为列

9q78igpj  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(328)

我有贷款数据,我想分组的日期,并通过不同的产品获得金额月
我的数据是这样的

disbursementdate | amount | product | cluster
2017-01-01       | 1000   | HL      | West
2018-02-01       | 1000   | PL      | East

所以在查询之后,我希望结果看起来像这样

Month            | HL   | PL
   January 2018     | 1000 | 0
   February 2018    | 100  | 1000

请注意,可能会有更多的产品,没有办法知道有多少独特的。。。所以呢 sum case when 不会有用的
我在苦苦挣扎

rsaldnfx

rsaldnfx1#

例如,您可以在mysql中构建要执行的代码

DROP TABLE IF EXISTS T;
CREATE TABLE T(disbursementdate DATE, amount INT, product VARCHAR(2), cluster VARCHAR(4));
INSERT INTO T VALUES
('2017-01-01'       , 1000   , 'HL'    ,   'West'),
('2017-01-01'       , 1000   , 'OL'    ,   'West'),
('2018-02-01'       , 1000   , 'PL'    ,   'East'),
('2018-02-01'       , 100    , 'HL'    ,   'West'),
('2018-02-01'       , 1000   , 'HL'    ,   'West');

SET @SQL = 

(SELECT CONCAT('SELECT DISBURSEMENTDATE,',
GROUP_CONCAT(CONCAT('SUM(CASE WHEN PRODUCT = ', CHAR(39),S.PRODUCT, CHAR(39),' THEN AMOUNT ELSE 0 END) AS ',S.PRODUCT))
,' FROM T GROUP BY DISBURSEMENTDATE;')
FROM 
(SELECT DISTINCT PRODUCT FROM T) S
)
;

PREPARE SQLSTMT FROM @SQL;
EXECUTE SQLSTMT;
DEALLOCATE PREPARE SQLSTMT;

+------------------+------+------+------+
| DISBURSEMENTDATE | HL   | OL   | PL   |
+------------------+------+------+------+
| 2017-01-01       | 1000 | 1000 |    0 |
| 2018-02-01       | 1100 |    0 | 1000 |
+------------------+------+------+------+
2 rows in set (0.00 sec)
bbuxkriu

bbuxkriu2#

您可以使用pandas和专门构建的方法 pd.DataFrame.pivot_table :

import pandas as pd

# read data

df = pd.read_csv('file.csv')

# extract month

df['Month'] = pd.to_datetime(df['disbursementdate']).apply(lambda x: x.replace(day=1))

# pivot results

res = df.pivot_table(index='Month', columns='product', values='amount',
                     aggfunc='sum', fill_value=0).reset_index()

# reformat month

res['Month'] = res['Month'].dt.strftime('%B %Y')

print(res)

product          Month    HL    PL
0         January 2017  1000     0
1        February 2018     0  1000

相关问题