使用Python从SQL Server中的两个表查询

时间:2019-06-21 17:48:29

标签: python sql-server pyodbc

当前使用以下代码从具有给定WHEREAND条件的一个表中获取数据:

import pyodbc 
import pandas as pd
conn = pyodbc.connect('Driver={SQL Server};'
                      'Server=XYZ\DA202P;'
                      'Database=Reporting;'
                      'Trusted_Connection=yes;')
cursor = conn.cursor()
query = pd.read_sql("""
               SELECT PID,NewValue,OriginalValue FROM Inc.ProblemAu
               where (ModifiedDate >= '2019-06-01 00:00:00.000' and ModifiedDate <= '2019-06-21 23:59:59.99')
               AND (NewValue='ntfy')
                """,conn)
query.to_excel('c:/temp/pydbc.xlsx')

如果PID是由在Inc.ProblemAu上运行的上述代码产生的,则我需要获取另一个带有Colums PID,X,y,z的表Inc.Problem。以上代码的结果可以包含PID的重复项,但其他列中的值唯一。

如何根据上述代码生成的所有唯一PID值从第二个表Inc.Problem获取数据(x,y,z列)?

1 个答案:

答案 0 :(得分:0)

只需使用INEXISTSJOIN子句:

IN

SELECT PID, x, y, z 
FROM Inc.Problem
WHERE PID IN
  (SELECT PID
   FROM Inc.ProblemAu
   WHERE (ModifiedDate >= '2019-06-01 00:00:00.000' 
     AND  ModifiedDate <= '2019-06-21 23:59:59.99')
     AND (NewValue='ntfy')
  )

EXISTS

SELECT PID, x, y, z 
FROM Inc.Problem main
WHERE EXISTS
  (SELECT 1
   FROM Inc.ProblemAu sub
   WHERE (sub.ModifiedDate >= '2019-06-01 00:00:00.000' 
     AND  sub.ModifiedDate <= '2019-06-21 23:59:59.99')
     AND (sub.NewValue='ntfy')
     AND main.PID = sub.PID
  )

JOIN

SELECT main.PID, main.x, main.y, main.z 
FROM Inc.Problem main
INNER JOIN
  (SELECT DISTINCT PID
   FROM Inc.ProblemAu sub
   WHERE (ModifiedDate >= '2019-06-01 00:00:00.000' 
     AND  ModifiedDate <= '2019-06-21 23:59:59.99')
     AND (NewValue='ntfy')
  ) sub
ON main.PID = sub.PID