Advertisement
Guest User

Untitled

a guest
May 16th, 2016
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. from terminaltables import AsciiTable
  2. import pymysql.cursors
  3. import time
  4.  
  5. # Connect to the database
  6. connection = pymysql.connect(host='localhost',
  7. user='--',
  8. password='--',
  9. db='olap_test',
  10. charset='utf8mb4',
  11. cursorclass=pymysql.cursors.DictCursor)
  12. start = time.time()
  13. try:
  14. with connection.cursor() as cursor:
  15. sql = "select country, customer_name, round(sum(amount),2) as amount, year(date1) as year from olap_data where country in ('Brazil', 'Venezuela', 'Argentina', 'Mexico') group by country, customer_name, year(date1)"
  16. cursor.execute(sql)
  17. result = cursor.fetchall()
  18. finally:
  19. connection.close()
  20.  
  21. def addRowTable(table, col1, col2, col3, col4, col5):
  22. table.append([str(col1), str(col2), str(col3), str(col4), str(col5)])
  23.  
  24. table_data = [['Land', 'Kunde', '%10s' % 'Umsatz 1994', '%10s' % 'Umsatz 1995', '%10s' % 'Umsatz 1996']]
  25. country = ''
  26. customer = ''
  27. for row in result:
  28. if country != row['country']:
  29. country = row['country']
  30. addRowTable(table_data, country, '', '', '', '')
  31. if customer != row['customer_name']:
  32. customer = row['customer_name']
  33. # get revenues from years 1994,1995 and 1996
  34. revenue_years = [item for item in result if item['country'] == country and item['customer_name'] == customer]
  35. revenue_per_year = [0.0, 0.0, 0.0]
  36. for revenue_year in revenue_years:
  37. if 1994 == revenue_year['year']:
  38. revenue_per_year[0] = revenue_year['amount']
  39. if 1995 == revenue_year['year']:
  40. revenue_per_year[1] = revenue_year['amount']
  41. if 1996 == revenue_year['year']:
  42. revenue_per_year[2] = revenue_year['amount']
  43. addRowTable(table_data, '', customer, "%10.2f" % revenue_per_year[0], "%10.2f" % revenue_per_year[1], "%10.2f" % revenue_per_year[2])
  44. table = AsciiTable(table_data)
  45. print(table.table)
  46. end = time.time()
  47. print("Time taken: %5.2f seconds" %(end - start))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement