我有一个查询,我试图在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
谢谢!
答案 0 :(得分:2)
回答问题2:如果你想要返回一行,你应该使用LEFT OUTER JOIN而不是INNER JOIN。 有关联接类型的说明,请参阅Wikipedia:http://en.wikipedia.org/wiki/Join_(SQL)
关于usertype的问题:我们需要有关数据库模式的更多信息。顺便说一下,我建议为你的别名使用一致的命名(比如员工e和人员p,而不是t1,t2等)。这使得查询更具可读性恕我直言。
答案 1 :(得分: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
答案 2 :(得分:0)
选择 t1.quoteID, t1.dateEntered, t1.insuredFirstName + t1.insuredLastName作为InsuredName, t2.FirstName + t2.LastName作为AgentName, t1.quoteType, t1.status, t3.noteDate, t3.usertype 从 quote_genericInformation t1 INNER JOIN tbl_agents t2 ON t1.createUserID = t2.AgentNumber LEFT JOIN注意事项t3 ON t1.quoteid = t3.quoteid AND t3.row_num = 1 ORDER BY t3.noteDate desc