简体   繁体   中英

provide column= value with selecting min date column ,compare 2 columns

I have following table

sec_id|pri_id   |date_col|  
abc|    1   |28-02-2017|    
bcd|    1   |09-01-2017|    
ef| 1   |   |
ghi|    2   |04-04-2017|    
jkl|    2   |05-05-2016|

If sec_id belong to same pri_id then select sec_id with oldest date and give it value 1 and other zero.

output something like this output table

|sec_id |pri_id |date_col  |new_column |
|abc    |1  |28-02-2017|    0|
|bcd    |1  |09-01-2017|    1|
|ef |1  |      |    0|
|ghi    |2  |04-04-2017|    0|
|jkl    |2  |05-05-2016|    1|

select f_id, s_id, case when min(cast(date_id as timestamp)) then 1 else 0 end as new_column from test_sc group by f_id,s_id. 

Plus there are other conditions too , if date_col null then take col_e ... if col_e =r then 1 as new new_col ,if col_e is null then take col_f ..if col_f with lowest value ..like wise 6 more conditions. but meanwhile just date_col .

select  *
       ,case 
            when pri_id = min(pri_id) over (partition by sec_id) 
            then 1 
            else 0 
        end as new_column

from    mytable

+-----+--------+------------+------------+
| dt  | sec_id |   pri_id   | new_column |
+-----+--------+------------+------------+
| ef  |      1 | (null)     |          0 |
| bcd |      1 | 2017-01-09 |          1 |
| abc |      1 | 2017-02-28 |          0 |
| jkl |      2 | 2016-05-05 |          1 |
| ghi |      2 | 2017-04-04 |          0 |
+-----+--------+------------+------------+

As far as your first question is concerned, you might try the following:

SELECT t1.sec_id,
       t1.pri_id,
       t1.date_col,
       CASE WHEN t1.date_col = t2.date_col THEN 1 ELSE 0 END AS new_column
FROM   my_table t1
JOIN   my_table t2
  ON   t1.pri_id = t2.pri_id
 AND   t2.date_col = (SELECT MIN(date_col)
                      FROM   my_table t3
                      WHERE  t2.pri_id = t3.pri_id)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM