只选择最高记录

时间:2018-02-14 07:08:21

标签: sql sql-server tsql

我有SQL喜欢这个

SELECT manjalink_id, printed_serial, full_name, vm.cu_id
from [dbfastsconfigdataref].[dbo].[v_manja_user_cuid] vm
INNER JOIN dbmanjaprofile.dbo.m_manja_user m on m.manjalink_id = 
vm.manja_user_id
INNER JOIN dbfastsconfigdataref.dbo.cdf_micard mi on mi.cu_id = vm.cu_id
where m.created_timestamp >= '2018-02-01'
order by m.created_timestamp, full_name

带输出

    Manjalink_id       printed_serial     full_name      cu_id
 ------------------------------------------------------------------
        101              00000123          alex          5556566
        102              00000124          alex          5556899
        103              00000126          max           8989899

我想这样:

 Manjalink_id       printed_serial     full_name      cu_id
 ------------------------------------------------------------------
        101              00000123          alex          5556566
        103              00000126          max           8989899

如何将结果作为所需的输出?

谢谢!

2 个答案:

答案 0 :(得分:1)

SELECT manjalink_id, printed_serial, full_name, cu_id
from
(SELECT manjalink_id, printed_serial, full_name, vm.cu_id, row_number() over (partition by full_name order by manjalink_id) rn
from [dbfastsconfigdataref].[dbo].[v_manja_user_cuid] vm
INNER JOIN dbmanjaprofile.dbo.m_manja_user m on m.manjalink_id = 
vm.manja_user_id
INNER JOIN dbfastsconfigdataref.dbo.cdf_micard mi on mi.cu_id = vm.cu_id
where m.created_timestamp >= '2018-02-01'
) a where rn = 1
order by full_name 

答案 1 :(得分:0)

尝试这样的事情。

使用Row_number()根据您的列生成序列号,然后选择所需的序列值。

select manjalink_id, printed_serial, full_name, cu_id  from (
SELECT manjalink_id, printed_serial, full_name, vm.cu_id ,ROW_NUMBER()over(partition by full_name order by manjalink_id) Rnum
from [dbfastsconfigdataref].[dbo].[v_manja_user_cuid] vm
INNER JOIN dbmanjaprofile.dbo.m_manja_user m on m.manjalink_id = 
vm.manja_user_id
INNER JOIN dbfastsconfigdataref.dbo.cdf_micard mi on mi.cu_id = vm.cu_id
where m.created_timestamp >= '2018-02-01'
)as a
where Rnum=1

注意:供参考检查Row_number()。此外还有很多网站可供了解