我一整天都在拔头发,有人可以帮我。我认为这可能很简单,但我不能完全得到我想要的东西。
表格中的数据如下所示
CallId ProblemDescription CurrentAction CurrentEngineer EventNumber
CON-00002 Respond to Call 0
WHS-00001 Respond to Call 0
WHS-00002 Respond to Call 0
WHS-00003 Respond to Call 0
WHS-00003 Fix Problem 1
WHS-00003 Problem Fixed 2
我想要做的是显示具有最大事件编号的CallId的所有列。即。
CallId ProblemDescription CurrentAction CurrentEngineer EventNumber
CON-00002 Respond to Call 0
WHS-00001 Respond to Call 0
WHS-00002 Respond to Call 0
WHS-00003 Problem Fixed 2
但是我无法弄清楚如何去做。
目前我正在使用
Select CallId, MAX(ProblemDescription), MAX(CurrentAction), MAX(CurrentEngineer),
MAX(EventNumber) FROM [Table] GROUP BY CallId
这显然如何单独返回每个coloumn的最大值。因此,在上面的情况下,CurrentAction列显示Respond to Call
而非Respond to Call
有人能告诉我怎么做吗?
由于
答案 0 :(得分:3)
我假设您正在寻找DENSE_RANK
:
WITH CTE AS
(
SELECT
CallId,
ProblemDescription,
CurrentAction,
CurrentEngineer,
EventNumber,
Rank = DENSE_RANK() OVER (PARTITION BY CallId ORDER BY EventNumber DESC)
FROM dbo.TableName
)
SELECT
CallId, ProblemDescription, CurrentAction, CurrentEngineer, EventNumber
FROM
CTE
WHERE
RANK = 1
如果您希望每CallId
只有一行,即使有多个广告EventNumber
使用ROW_NUMBER
,也要使用{{1}}。
答案 1 :(得分:1)
你想使用row_number():
select CallId, ProblemDescription, CurrentAction, CurrentEngineer, EventNumber
from (select t.*,
ROW_NUMBER() over (partition by callId order by eventnumber desc) as seqnum
from t
) t
where seqnum = 1
答案 2 :(得分:0)
使用此代码。 *仅在事件编号列上使用Max聚合。
SELECT CallID, Problem_Description, Current_Action, Current_Engineer, MAX( Event_Number ) FROM test.data GROUP BY CallID;
这可能对您有所帮助