0

我有一个查询,我试图在 SQL Server 2008 中编写以生成如下行:

quoteID | dateEntered | insuredName | agentName | quoteType | status | noteDate | userType

我目前有:

SELECT
    t1.quoteID,
    t1.dateEntered,
    t1.insuredFirstName + ' ' + t1.insuredLastName as insuredName,
    t2.FirstName + ' ' + t2.LastName as agentName,
    t1.quoteType,
    t1.status,
    t3.noteDate
FROM
    quote_genericInformation t1

INNER JOIN tbl_agents t2
    ON t1.createUserID = t2.AgentNumber

INNER JOIN 
    (SELECT quoteID, MAX(dateEntered) as noteDate
        FROM quote_notes GROUP BY quoteID) t3
    ON t1.quoteid = t3.quoteid

ORDER BY t1.quoteID

这会产生如下结果:

quoteID | dateEntered | insuredName | agentName     | quoteType | status | noteDate
54      | 01/01/2000  | First Last  | First Last    | apptype   | open   | 01/01/2000
  1. 我需要将用户类型添加为另一列,但是当我添加它时,我开始重复。
  2. 无论该quoteID是否存在quote_note,我都需要它始终显示一行
  3. 我需要这个来在注释中显示最新的用户类型(基于注释)

谢谢!

4

3 回答 3

2
WITH note AS (
    SELECT quoteID
        , dateEntered as noteDate 
        , usertype 
        , ROW_NUMBER() OVER (PARTITION BY quoteID ORDER BY dateEntered DESC) as row_num
    FROM quote_notes
)
SELECT
    t1.quoteID,
    t1.dateEntered,
    t1.insuredFirstName + ' ' + t1.insuredLastName as insuredName,
    t2.FirstName + ' ' + t2.LastName as agentName,
    t1.quoteType,
    t1.status,
    t3.noteDate,
    t3.usertype
FROM
    quote_genericInformation t1

INNER JOIN tbl_agents t2
    ON t1.createUserID = t2.AgentNumber
LEFT JOIN note t3
    ON t1.quoteid = t3.quoteid
    AND t3.row_num = 1
ORDER BY t1.quoteID
于 2013-10-22T18:42:59.910 回答
2

对问题 2 的回答:如果您希望始终返回一行,您应该使用 LEFT OUTER JOIN,而不是 INNER JOIN。有关连接类型的说明,请参见 Wikipedia:http://en.wikipedia.org/wiki/Join_(SQL)

至于关于用户类型的问题:那么我们需要更多关于数据库模式的信息。顺便说一句,我建议对您的别名使用一致的命名(例如员工 e 和人员 p,而不是 t1、t2 等)。恕我直言,这使查询更具可读性。

于 2013-10-22T18:39:45.940 回答
0

选择 t1.quoteID, t1.dateEntered, t1.insuredFirstName + t1.insuredLastName 作为 InsuredName, t2.FirstName + t2.LastName 作为 AgentName, t1.quoteType, t1.status, t3.noteDate, t3.usertype FROM quote_genericInformation t1 INNER JOIN tbl_agents t2 ON t1.createUserID = t2.AgentNumber LEFT JOIN note t3 ON t1.quoteid = t3.quoteid AND t3.row_num = 1 ORDER BY t3.noteDate desc

于 2013-10-23T12:44:03.743 回答