以下是一个示例数据集。
shareId mode shareLevel targetId targetItemId
26 1 5 0 2
32 1 5 0 21
33 2 1 1 21
34 1 3 0 21
我试图将结果作为结果:
shareId mode shareLevel targetId targetItemId
26 1 5 0 2
33 2 1 1 21
*因此我需要'shareId'字段。
*按TargetItemId分组,所以我只返回给定targetItemId的单个记录
*但我需要具有最高模式值的记录,因此在分组期间,我希望该字段具有MAX(模式)
这是我尝试的但是它无效:
select shareId FROM shares group by targetItemId having mode = MAX(mode)
它只返回:
shareId mode shareLevel targetId targetItemId
26 1 5 0 2
所以基本上,我如何为每个唯一的targetItemId获取shareId,但我想要具有最大模式的给定targetItemId的行。我该怎么做呢?
答案 0 :(得分:1)
您可以使用排名功能执行此操作:
select shareId, mode, shareLevel, targetId, targetItemId
from (select t.*,
row_number() over (partition by targetItemId order by mode desc) as seqnum
from t
) t
where seqnum = 1
这假定您只需要一行,即使重复模式的最大值也是如此。如果您想要所有值,请使用dense_rank
代替row_number
。
答案 1 :(得分:1)
这适用于任何rdbms:
select shareId
from shares s
join (select max(mode) as mode,targetItemId from shares group by targetItemId) s_max
on s.mode=s_max.mode
and s.targetItemId =s_max.targetItemId
答案 2 :(得分:0)
如果您使用MSSQL 2008+
,请尝试此
WITH latestRecord
AS
(
SELECT shareId, [mode] ,shareLevel ,targetId , targetItemId,
ROW_NUMBER() OVER (PARTITION BY targetItemId ORDER BY [mode] DESC) AS RN
FROM tableName
)
SELECT shareId, [mode] ,shareLevel ,targetId , targetItemId
FROM latestRecord
WHERE RN = 1