我需要一个空值来表示重复值

时间:2017-06-12 10:35:06

标签: database

我有一个问题

state_id  state_name  city_id  city_name  
--------  ----------  -------  -----------
       1  Karnataka         1  Bangalore  
       1  Karnataka         2  Mysore     
       1  Karnataka         3  Hubli      
       2  Maharastra        1  abc        
       2  Maharastra        2  xyz        

我应该要求输出如下

state_id  state_name      city_id  city_name  
--------  ----------      -------  -----------
       1  Karnataka          1  Bangalore  
       1  null               2  Mysore     
       1  null               3  Hubli      
       2  Maharastra         1  abc        
       2  null               2  xyz  

请帮助我摆脱这个

1 个答案:

答案 0 :(得分:0)

如上所述,

我已经解决了这个问题,

以下是脚本

SET @rn = 0; SET @sid = 0; SELECT state_id,city_id,city_name,@ sid1:= @ sid,@ sid:= state_id,IF(IF(@ sid1 = @ sid,@ rn:= @ rn + 1,@ rn:= 1)= 1,state_name, NULL)AS state_name FROM t2;

state_id city_id city_name @ sid1:= @ sid @sid:= state_id state_name

   1        1  Bangalore            0               1  Karnataka   
   1        2  Mysore               1               1  (NULL)      
   1        3  Hubli                1               1  (NULL)      
   2        1  abc                  1               2  Maharastra  
   2        2  xyz                  2               2  (NULL)    

感谢给出的提示