Python - передача значений из одного Dataframe в другой запрос - PullRequest
2 голосов
/ 10 июля 2019

Я пытаюсь выполнить SQL-запрос в Python, где я пытаюсь передать вывод Dataframe как часть предложения where.

import psycopg2
import pandas as pd
con = psycopg2.connect (db1_details)
con1 = psycopg2.connect (db2_details)

В нем есть все сгенерированные счета

data = pd.read_sql("""select bill_id from sales where date > '2019-01-01'""", con = con)

Теперь я пытаюсь вытянуть всех клиентов, которые создали счет после 2019-01-01, полученного в предыдущем запросе и хранящегося в data

customer_details = f"""select cust_name, bill_id from customers where bill_id in {data}"""

Я не уверен, как передатьзначение из кадра данных в другой запрос как часть цикла.

Редактировать:

Просмотр data.head()

bill_id
1001
1002
1003
1006
1007

Ответы [ 3 ]

1 голос
/ 10 июля 2019
  1. Извлечение уникальных bill_ids из данных
  2. преобразовать этот список в кортеж и отправить его в запрос
unique_bill_id = list(data["bill_id"].unique())
if len(unique_bill_id ) == 1:
     unique_bill_id.append(unique_key[0])

query = "select cust_name, bill_id from customers where bill_id in {};".format(tuple(unique_bill_id))
df = pd.read_sql_query(query,con=con1)
1 голос
/ 10 июля 2019

Если имя столбца bill_id и требуется цикл для каждого уникального клиента:

for cust in data['bill_id'].unique():
    customer_details = f"""select cust_name, bill_id from customers where bill_id in ({cust})"""
    print (customer_details)
    select cust_name, bill_id from customers where bill_id in (1001)
    select cust_name, bill_id from customers where bill_id in (1002)
    select cust_name, bill_id from customers where bill_id in (1003)
    select cust_name, bill_id from customers where bill_id in (1006)
    select cust_name, bill_id from customers where bill_id in (1007)

    data = pd.read_sql(customer_details, con=con1)

Или, если нужны все уникальные клиенты:

all_data = ', '.join(data['bill_id'].unique().astype(str))
customer_details = f"""select cust_name, bill_id from customers where bill_id in ({all_data})"""
print (customer_details)
select cust_name, bill_id from customers where bill_id in (1001, 1002, 1003, 1006, 1007)

data = pd.read_sql(customer_details, con=con1)
0 голосов
/ 10 июля 2019

Вы можете присоединиться к 2 столам, как это

select distinct c.cust_name, c.bill_id 
from customers as c
join sales as s on c.bill_id=s.bill_id and s.date > '2019-01-01'

Это может быть более эффективным.

...