Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

sql - I have a unique or distinct recors in all the column, table

I need a unique record all the table and all the column how can I get

Table1 Col1 col2 col3 col4 col5

  1.    A.     P.      20.   21
    
  2.    B.     Q.     18.   19
    
  3.    C.     R       17.   16
    

Table2 Col1 col2 col3 col4 col5

  1.    A.     P.      51   58
    
  2.    B.     Q.     60   65
    
  3.    C.     R       18   25
    
  4.    D.     S.      33.   31
    

Table3 Col1 col2 col3 col4 col5

  1.    A.     P.      60.    13
    
  2.    B.     Q.     75      61
    
  3.    E       t      100   108
    
  4.    F.      U.      91.   98
    

Output of table (I need like dz output)

Col1 col2 col3 col4 col5

  1.    A.     P.      20.   21
    
  2.    B.     Q.     18.   19
    
  3.    C.     R       17.   16
    
  4.    D.     S.      33.   31
    
  5.    E.     T.       100  108
    
  6.    F.     U.       91.   98
    
question from:https://stackoverflow.com/questions/65897331/i-have-a-unique-or-distinct-recors-in-all-the-column-table

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To get all the unique rows you can combine all the records from all three tables using union all and use distinct to get unique rows.

select distinct col2 ,col3 ,col4 ,col5 from (
select col2 ,col3 ,col4 ,col5 from Table1 
union all
select col2 ,col3 ,col4 ,col5 from Table2
union all
select col2 ,col3 ,col4 ,col5 from Table3 )T

Or if you wan to show first record of each unique col1 and col2 value as in your output table use below query (I didn't use Col1 in the query since it's serial number for that table only):

with cte as (
select row_number() over (partition by Col2,Col3 order by sl)rn, col2 ,col3 ,col4 ,col5 from (
    select 1 sl, col2 ,col3 ,col4 ,col5 from Table1 
    union all
    select 2 sl, col2 ,col3 ,col4 ,col5 from Table2
    union all
    select 3 sl ,col2 ,col3 ,col4 ,col5 from Table3 )T
)select row_number() over (order by col1),Col1,Col2, Col3, Col4 from cte where rn=1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...