简体   繁体   中英

writing a query to to generate two records from one record based on some condition

I have table with columns:

  • flag1
  • flag2
  • flag1_column1
  • flag1_column2
  • flag1_column3
  • flag2_column1
  • flag2_column2
  • flag2_column3

my requirement is:

  • If both flag1 and flag2 have value true then in result I should get two records:

    1. flag1, flag1_column1, flag1_column2, flag1_column3
    2. flag2, flag2_column1, flag2_column2, flag2_column3

my second requirement:

If flag1 is null or 0 then I should get only one record:

flag2 ,flag2_column1, flag2_column2, flag2_column3 

my third requirement:

If flag2 is null or 0 then I should get only one record:

flag1 , flag1_column1, flag1_column2, flag1_column3

This is query that returns desired result:

select flag1 as flag,
       flag1_column1 as c1, 
       flag1_column2 as c2, 
       flag1_column3 as c3 
from t where flag1=1
union
select flag2 as flag,
       flag2_column1 as c1, 
       flag2_column2 as c3, 
       flag2_column3 as c3 
from t where flag2=1

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