2017-04-07 30 views
0
import sqlite3 

db = sqlite3.connect('newdb.db') 
team_list = ['Munster', 'Leinster', 'Ulster', 'Glasgow'] 
cursor = db.cursor() 
for i in range(len(team_list)): 
    team_names = team_list[i].upper() 

    searchStr = '%' + team_names + '%' 
    cursor.execute('select * from tickets where Name LIKE ?', (searchStr,)) 

teams_points = cursor.fetchall() 
print teams_points 

cursor.close() 
db.close() 

這是我的python代碼,用於顯示newdb.db中「票」表中的所有數據。我有一個名單與團隊名稱,我希望能夠搜索數據庫中的這些團隊名稱,並計算出售門票的信息。 picture of database將來自dabtabse文件的信息放入列表

[(u'MUNSTER', 5, u'First Round'), (u'MUNSTER', 5, u'First Round'), 
(u'MUNSTER', 8, u'Second Round'), (u'MUNSTER', 10, u'Both Rounds')] 
[(u'LEINSTER', 2, u'Second Round'), (u'LEINSTER', 16, u'First Round'), 
(u'LEINSTER', 5, u'Both Rounds'), (u'LEINSTER', 6, u'Both Rounds'), 
(u'LEINSTER', 3, u'First Round')] 
[(u'ULSTER', 10, u'Second Round')] 
[(u'GLASGOW', 4, u'First Round')] 

以上是我的輸出,當我運行該腳本,我希望能夠把每個團隊成列表,

team_list=['team_name', 'total first round tickets', 'second round tickets'] 


munster_list = ['MUNSTER', '20', '18'] 
leinster_list = ['LEINSTER','30','13'] 
ulster_list = ['ULSTER','0','10'] 
glasgow_list = ['GLASGOW','4','0'] 

所以後來打印的清單,我可以只使用打印munster_list

回答

0

使用GROUP BY從每個組的行中獲取一個輸出行。使用CASE expressions總結出只有特定的值:

SELECT Name, 
     sum(CASE WHEN Type IN ('First Round', 'Both Rounds') 
       THEN Amount 
       ELSE 0 
      END) AS "first round tickets", 
     sum(CASE WHEN Type IN ('Second Round', 'Both Rounds') 
       THEN Amount 
       ELSE 0 
      END) AS "second round tickets" 
FROM tickets 
GROUP BY Name 
ORDER BY Name; 
+0

我是realtively新的Python,我保證在那裏把這個 – dodger

+0

這是一個SQL查詢。你把它給予'execute()'。非常感謝 –

+0

工作 – dodger

相關問題