SQL组合两个查询

时间:2014-04-14 14:26:48

标签: sql sql-server

以下代码选择两个表中的记录,其中email和dob都匹配另一条记录(所有重复项......)

SELECT 
    AccountName, 
    EmailAddress, 
    DateOfBirth
FROM 
(
    SELECT 
        a.AccountName, 
        a.EmailAddress, 
        u.DateOfBirth, 
        COUNT(*) over (partition by a.EmailAddress, u.DateOfBirth) AS cnt
    FROM Account AS a 
    JOIN [User] AS u ON a.AccountID = u.AccountID              
) ua                
WHERE cnt > 1
AND EmailAddress IS NOT null
AND DateOfBirth IS NOT null     
ORDER BY EmailAddress, DateOfBirth 

我还想在此表中添加一个名为' Audit'的另一个表中的字段。我们可以使用LoginID加入它们,但是LoginID在Audit表中具有一对多的关系。即一个LoginID可以有很多审核。

我想添加Audit StartDate列。以下查询允许我按日期识别最新的审核。

         SELECT  a.LoginID as AuditLoginID,
         MAX(StartDate) as StartDate
         FROM    Audit as a
         GROUP BY  a.LoginID
         ORDER BY a.StartDate

是否有人能够建议我如何组合这两个查询,以便我的原始查询有一个连接到Audit表,显示一个' StartDate'最新审计开始日期的一栏?

2 个答案:

答案 0 :(得分:1)

您应该考虑使用correlated subquery。这将避免构建另一个数据库对象来支持此查询,它是一个相对标准的SQL构造。

示例:

SELECT 
    AccountName, 
    EmailAddress, 
    DateOfBirth
FROM 
(
    SELECT 
        a.AccountName, 
        a.EmailAddress, 
        u.DateOfBirth, 
        a.LoginID,
        COUNT(*) over (partition by a.EmailAddress, u.DateOfBirth) AS cnt
    FROM Account AS a 
    JOIN [User] AS u ON a.AccountID = u.AccountID              
) ua           
join Audit as a 
  on a.LoginID = au.LoginID     
WHERE cnt > 1
AND EmailAddress IS NOT null
AND DateOfBirth IS NOT null     
AND a.startdate = (SELECT MAX(StartDate) as StartDate
                   FROM    Audit as b
                   WHERE b.LoginID = a.LoginID)
ORDER BY EmailAddress, DateOfBirth 

答案 1 :(得分:0)

以下是对我评论的扩展:

CREATE VIEW MostRecentLogins AS
  (
     SELECT a.LoginID as AuditLoginID,
            MAX(StartDate) as StartDate
       FROM Audit as a
      GROUP BY a.LoginID
  )

然后,您可以将MostRecentLogins视图加入到其他查询中。从您的帖子中不清楚哪个列与LoginId(来自Audit表)相对应,但查询看起来像这样:

SELECT a.AccountName, 
       a.EmailAddress, 
       u.DateOfBirth,
       MRL.StartDate
  FROM 
     (
       SELECT a.AccountName, 
              a.EmailAddress, 
              u.DateOfBirth, 
              COUNT(*) over (partition by a.EmailAddress, u.DateOfBirth) AS cnt
         FROM Account AS a 
              JOIN [User] AS u 
                       ON a.AccountID = u.AccountID              
     ) ua
     INNER JOIN MostRecentLogins MRL
         ON MRL.LoginID = a.LoginID    -- not sure what column should be on the RHS of this..
  WHERE cnt > 1
    AND EmailAddress IS NOT null
    AND DateOfBirth IS NOT null     
  ORDER BY EmailAddress, DateOfBirth