我有一张像
这样的表ParsereplyId Message Callid status EMailid subject
------------------------------------------------------------------------
1 hi 2222 Replied g.m.p@m.com Log a cll
2 hello 2222 Replied g.m.p@m.com Re:
3 hi2 2222 New g.m.p@m.com Re:log a cll
4 hello2 2223 Read g.p@m.com Log a cldf
5 how r u 2223 New g.p@m.com Re:Log a
从上表我想获得以下输出:
ParsereplyId Message Callid status EMailid subject
-------------------------------------------------------------------
3 hi2 2222 New g.m.p@m.com Re:log a cll
5 how r u 2223 New g.p@m.com Re:Log a
我尝试过以下查询。 但我想在左外连接
中做到这一点SELECT A.[ParsedReplyId]
, A.[EMailId]
, A.[Message]
, A.[CallId]
, [UM_User].[UserName]
FROM IM_IncidentReplyMail AS A
INNER JOIN
(SELECT MAX(ParsedReplyId) AS parseid
FROM [IM_IncidentReplyMail]
GROUP BY [CallId]) AS B
INNER JOIN
[UM_User] ON [UM_User].[EmailId] = A.[EmailId]
WHERE
B.parseid = A.[ParsedReplyId]
如何实现上面的sql查询到内连接?
编辑:我纠正了上面的错误
UM_USer表包含username, emailid
,根据两个表中的电子邮件ID,我可以获得该邮件的用户名。
编辑2: 我可以使用左外连接而不是像
那样使用内连接 SELECT A.[ParsedReplyId]
, A.[EMailId]
, A.[Message]
, A.[CallId]
, [UM_User].[UserName]
FROM IM_IncidentReplyMail AS A
LEFT OUTER JOIN
(SELECT MAX(ParsedReplyId) AS parseid
FROM [IM_IncidentReplyMail]
GROUP BY [CallId]) AS B
ON 1=1
LEFT OUTER JOIN
[UM_User] ON [UM_User].[EmailId] = A.[EmailId]
WHERE
B.parseid = A.[ParsedReplyId]
这里我使用了1 = 1条件,这不是在查询中使用的正确方法。它让我的代码变得丑陋。所以我请你帮忙解决这个问题。
答案 0 :(得分:1)
我已根据您所需的输出修改了查询
DECLARE @Table1 TABLE
(Id INT, Message VARCHAR(7), Call INT, status VARCHAR(7), EMail VARCHAR(11), subject VARCHAR(12))
;
INSERT INTO @Table1
(Id, Message, Call, status, EMail, subject)
VALUES
(1, 'hi', 2222, 'Replied', 'g.m.p@m.com', 'Log a cll'),
(2, 'hello', 2222, 'Replied', 'g.m.p@m.com', 'Re:'),
(3, 'hi2', 2222, 'New', 'g.m.p@m.com', 'Re:log a cll'),
(4, 'hello2', 2223, 'Read', 'g.p@m.com', 'Log a cldf'),
(5, 'how r u', 2223, 'New', 'g.p@m.com', 'Re:Log a')
;
SELECT T.Id,
TT.Message,
TT.Call,
TT.status,
TT.EMail,
TT.subject
FROM @Table1 tt
LEFT OUTER JOIN
(
SELECT Id,
MAX(subject) OVER(PARTITION BY call ORDER BY call) subject,
MAX(Message) OVER(PARTITION BY call ORDER BY call) Message FROM @Table1)T
ON T.Id = TT.Id AND T.Message = TT.Message AND T.subject = TT.subject
WHERE T.id IS NOT NULL