在我开始编写 Python 脚本之前,我想看看单独使用 MySQL 是否可以产生结果。
我有一个产品清单:
PID Product
-----------
1 AAA
2 ABC
3 BAC
4 CAB
5 CBA
我有一份多次订购这些产品的公司名单:
CID PID
-------
1 1
2 3
1 5
3 2
1 1
2 3
期望的结果:
CID AAA ABC BAC CAB CAB CBA
---------------------------
1 Y Y
2 Y
3 Y
我将如何在 Python 中做到这一点?
- 创建包含列的临时表 (CID AAA ABC BAC CAB CAB CBA)
- 当所需的列匹配时,运行 2 个循环并更新所需的表。
只是想看看是否存在唯一的 MySQL 解决方案。
ps:这只是一个示例,实际问题只有100个产品和1000个公司。我通过在 Excel 中进行转置为 100 个产品创建了一个临时表,并将其转换为 MySQL 表。
以下是我最终采用的方法。谢谢你们的反馈。
########### Python script to generate the MySQL query ##############
#MySQL Connection String Goes here#
#Generate MySQL 'CASE' logic
cursor = db.cursor()
if __name__ == '__main__':
cursor.execute("select PID, Product from products")
productlist = cursor.fetchall()
for product in productlist:
print ("max(case when PID = %s then 'Y' else '' end) as `%s`,") % (product[0], product[1])
db.close()
按照 nick 建议的格式使用生成的查询。
select cid,
max(case when pid = 1 then 'Y' else '' end) as AAA,
max(case when pid = 2 then 'Y' else '' end) as ABC,
max(case when pid = 3 then 'Y' else '' end) as BAC,
max(case when pid = 4 then 'Y' else '' end) as CAB,
max(case when pid = 5 then 'Y' else '' end) as CBA
from companies
group by cid