我有一个如下所示的结果集:
正如您所看到的,某些contactID
会以相同的QuestionResponse
重复。并且有一个具有不同的QuestionResponse
(带有红线的那个)。
我希望按ContactID
对此进行分组,但选择后一行。例如:如果是ContactID = 78100299
,我想选择CreateDate = 17:00:44.907
(或rowNum = 2)的行。
我试过这个:
select
ContactID,
max(QuestionResponse) as QuestionResponse,
max(CreateDate) as CreateDate
from
theResultSet
group by
ContactID
这不起作用,因为同一QuestionResponse
可能有contactID
2,然后是1。在这种情况下,后者将是响应1而不是2的那个。
谢谢你的帮助。
答案 0 :(得分:3)
我会这样使用ROW_NUMBER():
WITH Query AS
(
SELECT rowNum, ContactID, QuestionResponse, CreateDate,
ROW_NUMBER() OVER (PARTITION BY ContactID ORDER BY CreateDate DESC) Ordered
FROM theResultSet
)
SELECT * FROM Query WHERE Ordered=1
答案 1 :(得分:0)
如果您的SQL引擎可以处理它,这可能会有用......
SELECT trs1.*
FROM theResultSet trs1
INNER JOIN
(SELECT ContactID, max(CreateDate) as CreateDate
FROM theResultSet
GROUP BY ContactID) trs2
ON trs1.ContactID = trs2.ContactID
AND trs1.CreateDate = trs2.CreateDate
最终结果将是来自theResultSet的所有行,其中创建日期是最大创建日期。
答案 2 :(得分:0)
这也应该有效:
SELECT
ContactID, QuestionResponse,CreateDate
FROM (
select rowNum, ContactID, QuestionResponse,CreateDate,
max(rowNum) over(partition by ContactID) as maxrow
from theResultSet
) x
WHERE rowNum=maxrow