两个表MS SQL Server 2008中的一列不同

时间:2015-01-15 20:34:04

标签: sql sql-server database sql-server-2008

我想仅对CustomerID应用distinct并获取最新记录,因为我在table1中有RecordUpdate_date列。

我写了这个查询,但我遗漏了一些行(记录)并获得了重复的记录。

请帮助我。 感谢

表1:

CustomerID, CustomerName, UpdateDate

表2:

CustomerID, DateofBirth

我的查询:

SELECT a.CustomerID
       ,a.CustomerName
       ,a.RecordUpDate_date
       ,b.DateofBirth
    FROM Table1 AS a
    INNER JOIN (
                 SELECT CustomerID
                       ,MAX(RecordUpdate_date) AS max_RecordUpdate_date
                    FROM Table1
                    GROUP BY CustomerID
               ) AS abc
        ON abc.CustomerID = a.CustomerID
           AND abc.max_RecordUpdate_date = a.RecordUpdate_date
    INNER JOIN Table2 AS b
        ON b.CustomerID =  a.CustomerID
    INNER JOIN (
                 SELECT CustomerID
                       ,MAX(DateofBirth) AS max_dob
                    FROM table2
                    GROUP BY CustomerID
               ) AS m
        ON m.CustomerID = a.Customer
           AND m.max_cus = c.DateofBirth

3 个答案:

答案 0 :(得分:1)

有很多方法可以获得最新记录。我一直使用的个人使用ROW_NUMBER() http://msdn.microsoft.com/en-us/library/ms186734.aspx

首先在CTE中,我们根据customerid和desc date字段对行进行编号。接下来,您选择rn =1这里只获得每位客户的最新记录。

;WITH   CTE
          AS (
               SELECT customerID
                   ,customerName
                   ,UpdateDate
                   ,ROW_NUMBER() OVER ( PARTITION BY customerID ORDER BY UpdateDate DESC ) AS rn
                FROM table1 AS a
             )
    SELECT a.customerID
           ,a.CustomerName
           ,a.UpdateDate
           ,b.DateOfBrith
        FROM CTE a
        JOIN table2 AS b
            ON a.customerId = b.CustomerID
        where a.rn = 1

答案 1 :(得分:0)

试试这个:

;WITH    CTE
      AS ( SELECT   CustomerID ,
                    MAX(UpdateDate) max_RecordUpdate_date
           FROM     dbo.Table1
           GROUP BY CustomerID
         ),
    CTE1
      AS ( SELECT   CustomerID ,
                    MAX(DateofBirth) max_dob
           FROM     dbo.Table2
           GROUP BY CustomerID
         )
SELECT  CTE.CustomerID ,
        CustomerName ,
        max_RecordUpdate_date ,
        max_dob ,
        FLOOR(( CAST (max_RecordUpdate_date AS INTEGER)
                - CAST(max_dob AS INTEGER) ) / 365.25) [Age]
FROM    CTE
        INNER JOIN Table1 ON Table1.CustomerID = CTE.CustomerID
                             AND Table1.UpdateDate = CTE.max_RecordUpdate_date
        LEFT JOIN CTE1 ON CTE1.CustomerID = CTE.CustomerID   

答案 2 :(得分:0)

SELECT a.CustomerId, a.CustomerName, a.UpdateDate, b.DateofBirth
FROM Table1 a
INNER JOIN (SELECT CustomerId, MAX(UpdateDate) as UDate
            FROM Table1
            GROUP BY CustomerId
            )  maxdate  ON a.CustomerId = maxdate.CustomerId
                        AND a.UpdateDate = maxdate.UDate
INNER JOIN Table2 b ON a.CustomerId = b.CustomerId

如果您有多个customerid记录并且已更新,请使用SELECT DISTINCT。