我可以得到一些帮助来定义一个sqlite查询吗?

camsedfj  于 2023-08-06  发布在  SQLite
关注(0)|答案(1)|浏览(109)

我有以下数据表:

df = pd.DataFrame({'Well': ['A', 'A', 'B', 'B'],
                   'BP': [380., 25., 24., 360.],
                   'ng': [1., 10., 1., 10.],
                  'Band A': [True, False, False, True],
                  'Band B': [False, True, True, False]})

字符串
我需要帮助创建一个sql查询,如果在“Well”中满足以下条件,则返回true:“Band A”为“True”,“Band A”的“ng”大于“Band B”的“ng”
我做了以下不成功的尝试,被卡住了:

sqlcmd = '''
SELECT
    Well,
    ng,
    CASE
        WHEN Band_A = True AND ng > (SELECT ng FROM df WHERE Band_B = True) THEN 'True'
        ELSE 'False'
    END AS Duplicate
FROM df
ORDER BY Well;'''

pp.pprint(pysqldf(sqlcmd).head())

bfhwhh0e

bfhwhh0e1#

我跳过Pandas并演示如何在纯SQLite中完成此操作。它应该是可翻译的。

import os
import sqlite3

db = sqlite3.connect('76766531.db')

db.executescript('''
create table bands(
  well varchar(1) not null,
  bp int not null,
  ng int not null,
  band_a boolean not null,
  band_b boolean not null
);

insert into bands(well, bp, ng, band_a, band_b) values
('A', 380,  1, true, false),
('A',  25, 10, false, true),
('B',  24,  1, false, true),
('B', 360, 10, true, false);
''').close()

cur = db.execute('''
select side_a.well,
       side_a.ng > side_b.ng as predicate
from bands as side_a
join bands as side_b
    on side_a.well = side_b.well
   and side_a.band_a
   and side_b.band_b;
''')
try:
    for well, predicate in cur.fetchall():
        print(f'{well}: {predicate == 1}')
finally:
    cur.close()

个字符

相关问题