我想提取與我的兩個數據集中存在的股票相對應的數據(在下面的代碼中給出)。Python中的sqlite3交集
這是我的數據:
#(stock,price,recommendation)
my_data_1 = [('a',1,'BUY'),('b',2,'SELL'),('c',3,'HOLD'),('d',6,'BUY')]
#(stock,price,volume)
my_data_2 = [('a',1,5),('d',6,6),('e',2,7)]
這裏是我的問題:
問題1:
我試圖提取的價格,推薦和體積對應於資產 'A' 。我非常希望得到這樣一個元組:
(u'a',1,u'BUY',5)
問題2:
如果我想獲得交集的所有股票(不只是「一」的問題1),在此如果是庫存「a」和庫存「d」,那麼我的期望輸出變爲:
(u'a',1,u'BUY',5)
(u'd',6,u'BUY',6)
我應該怎麼做?
這是我嘗試(問題1):
import sqlite3
my_data_1 = [('a',1,'BUY'),('b',2,'SELL'),('c',3,'HOLD'),('d',6,'BUY')]
my_data_2 = [('a',1,5),('d',6,6),('e',2,7)]
#I am using :memory: because I want to experiment
#with the database a lot
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute('''CREATE TABLE MY_TABLE_1
(stock TEXT, price REAL, recommendation TEXT)''')
c.execute('''CREATE TABLE MY_TABLE_2
(stock TEXT, price REAL, volume REAL)''')
for ele in my_data_1:
c.execute('''INSERT INTO MY_TABLE_1 VALUES(?,?,?)''',ele)
for ele in my_data_2:
c.execute('''INSERT INTO MY_TABLE_2 VALUES(?,?,?)''',ele)
conn.commit()
# The problem is with the following line:
c.execute('select* from my_table_1 where stock = ? INTERSECT select* from my_table_2 where stock = ?',('a','a') )
for entry in c:
print entry
我沒有得到任何錯誤,也沒有輸出,這樣的東西是清楚了。
我也試過這條線:
c.execute('select* from my_table_1 where stock = ? INTERSECT select volume from my_table_2 where stock = ?',('a','a')
,但它不工作,我得到這個錯誤:
c.execute('select* from my_table_1 where stock = ? INTERSECT select volume from my_table_2 where stock = ?',('a','a') )
sqlite3.OperationalError: SELECTs to the left and right of INTERSECT do not have the same number of result columns
我明白爲什麼我會有不同數量造成的列,但不要」很明顯,爲什麼會觸發一個錯誤。
我該怎麼做?
非常感謝您提前
非常感謝您的回答;它完全符合我的要求。另外,謝謝你的解釋,我需要那:)。 – Akavall 2012-03-28 17:52:57