【发布时间】:2017-09-25 04:33:26
【问题描述】:
我有一张如下表:
**ID tDate Product Price Quantity BuySell Status**
1 10-May-17 pppp $12 20 Buy Null
2 12-May-17 tttt $10 20 Sell Null
3 12-May-17 tttt $10 20 Buy Null
4 18-May-17 pppp $14 20 Sell Null
5 18-May-17 pppp $14 20 Buy Null
6 18-May-17 pppp $14 20 Sell Null
我需要更新名为 STATUS 的字段,并将其设置为“匹配”,只要找到具有相同 tDate、产品、价格和数量且不等于 BuySell 的货币对。
以下是想要的结果:
**ID tDate Product Price Quantity BuySell Status**
1 10-May-17 pppp $12 20 Buy Null
2 12-May-17 tttt $10 20 Sell Matched
3 12-May-17 tttt $10 20 Buy Matched
4 18-May-17 pppp $14 20 Sell Matched
5 18-May-17 pppp $14 20 Buy Matched
6 18-May-17 pppp $14 20 Sell Null
注意#6 是如何不匹配的,因为它只能与另一个 null 匹配。
我希望我可以用一条 SQL 语句来执行此操作。
我现在正在做的可能是最糟糕的方法: 我在 python 中加载到 pandas 数据框,然后循环遍历每一行来比较它们。
s = "SELECT ID, Account, product, Price, tDate, BuySell, Qty" + \
"FROM Table " + \
"WHERE Status IS NULL " + \
"ORDER BY Account, product, tDate, Price, Qty"
df = pd.read_sql(s, conn)
for i in range(len(df.index)-1):
if df.iloc[i, 1] == df.iloc[i+1, 1] \
and df.iloc[i, 2] == df.iloc[i+1, 2] \
and df.iloc[i, 3] == df.iloc[i+1, 3] \
and df.iloc[i, 4] == df.iloc[i+1, 4] \
and df.iloc[i, 5] != df.iloc[i+1, 5] \
and df.iloc[i, 6] == df.iloc[i+1, 6]:
s = "UPDATE Temp_Fees " + \
"SET Strategy = 'UNALLOCATED \ CANCELLED' " + \
"WHERE ID = " + str(df.iloc[i,0]) + \
" OR ID = " + str(df.iloc[i + 1, 0])
#custom function that will execute and commit statement
bb.EXECUTE(s)
#avoid reading a matched row
i = i + 1
谢谢
【问题讨论】:
-
每个日期可以有超过一对的买卖吗?
-
@vkp 是的,甚至在示例中(记录 4、5、6)。编辑:我承认,该示例并未明确表明每天可以有多个匹配项,但连同描述“#6 不匹配,因为它只能与另一个 null 匹配”一起,它确实隐含地这么说。
-
编辑问题并解释当键之间存在重复时该怎么办。
标签: python sql oracle pandas plsql