仅选择1个数据,但行数仍为3

时间:2017-10-05 08:01:56

标签: sql

有没有办法呢?

来自:

(Select  MBLNo,HBLNo from tblCargo where MBLNo = 'M00000001' )

1 | M00000001 | H0003
2 | M00000001 | H0003
3 | M00000001 | H0003

要:

1 | M00000001 | H0003
2 | NULL      | H0003
3 | NULL      | H0003

2 个答案:

答案 0 :(得分:1)

虽然我认为在显示数据的应用程序中做得更好,但在SQL中可以这样做:

select id, 
       case 
         when row_number() over (partition by mblno order by id) = 1 then mblno 
         else null 
       end as mblno
from tblcargo
where ...

答案 1 :(得分:1)

检查这个。

;WITH CTE
     AS (
     SELECT *,
            ROW_NUMBER() OVER(PARTITION BY MBLNO ORDER BY MBLNo) rno
     FROM temp)
     SELECT CASE
                WHEN rno = 1
                THEN MBLNo
                ELSE NULL
            END AS MBLNO,
            HBLNo
     FROM CTE;

期望输出:

MBLNo       HBLNo
M00000001   H0003
NULL        H0003
NULL        H0003