不同表中的SQL 2列不同

时间:2013-04-30 16:42:26

标签: sql sql-server sql-server-2008 distinct

这已经解决了,我需要在SQL中连接4个表,不同表中的2列是不同的。到现在为止,我会一直得到重复的行。

我有4个表,我试图加入1个查询。

我需要创建一个类似于以下内容的报告:

quoteid | dateEntered | insuredName | admin initials | quoteType | status | last note usertype

Select quoteID,insuredFirstName,insuredLastName,quoteType,status, firstname, lastname, adminInitial, userType
from (SELECT Row_Number() Over(Partition by A.quoteid  order by A.quoteid ) as Row , A.quoteID, A.insuredFirstName, A.insuredLastName, A.quoteType, A.status, B.firstName, B.lastName, left(C.firstName,1) + left(C.lastName,1) as adminInitial, D.userType
    FROM quotes A
    INNER JOIN tbl_agents B
    ON A.createUserID = B.AgentNumber
    INNER JOIN tbl_admins C
    ON A.assignedID = C.ID
    INNER JOIN
        (SELECT 
            quoteID, userType
            FROM quote_notes) D
            ON A.quoteID = D.quoteID) as t where row=1 

2 个答案:

答案 0 :(得分:2)

尝试将 DISTINCT inner查询移至outside查询。

答案 1 :(得分:1)

请尝试使用Row_Number()这样使用Partition by ......

  Select quoteID,insuredFirstName,insuredLastName,quoteType,status from (SELECT Row_Number() Over(Partition by quoteid ,Name1  order by quoteid ) as Row , A.quoteID, A.insuredFirstName, A.insuredLastName, A.quoteType, A.status, B.firstName, B.lastName, left(C.firstName,1) + left(C.lastName,1) as adminInitial, D.userType
        FROM quotes A
        INNER JOIN tbl_agents B
        ON A.createUserID = B.AgentNumber
        INNER JOIN tbl_admins C
        ON A.assignedID = C.ID
        INNER JOIN
            (SELECT 
                quoteID, userType
                FROM quote_notes) D
                ON A.quoteID = D.quoteID) as t where row=1