Before I set out to write a Python script, I want to see if MySQL alone can produce the result.
I have a list of products :
PID Product
-----------
1 AAA
2 ABC
3 BAC
4 CAB
5 CBA
I have a list of companies ordering these products several times :
CID PID
-------
1 1
2 3
1 5
3 2
1 1
2 3
The desired result :
CID AAA ABC BAC CAB CAB CBA
---------------------------
1 Y Y
2 Y
3 Y
How I would do this in Python?
- Create a temp table with columns (CID AAA ABC BAC CAB CAB CBA)
- Run 2 loops and update the desired table when the desired column matches.
Just curious to see if there exists a MySQL only solution.
p.s : This is just a sample and the actual problem has few 100 products and few 1000 companies. I created a temp table for 100 products by doing a transpose in Excel and converted it to a MySQL table.
Following is the approach I finally resorted to. Thanks for the feedback guys.
########### 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()
Use the generated query in the format as suggested by 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
1 Answer