简体   繁体   中英

Compare two or more columns in sql

Database structure :

  • Table name : question
  • Columns : qid, que, a, b, c, d, ans

Dummy data 1:

Qid-1
Que-what is capital of india ?
A- mumbai
B- delhi
C-kolkata
D-chennai
Ans-B

Dummy data 2:

Qid-2
Que-formula of water ?
A- h2O
B- h30
C-h40
D-h50
Ans-A

Desired output :

Que                                ans
what is capital of india ?         Delhi
Formula of water ?                 H20

How to compare last column ( ans ) with other columns ( a, b, c, d )?

I need a SQL query for that..

Thanks in advance.

As i inderstood you need decode ans into proper column. Assuming that answer 'A' means: return value of column a, answer 'B' - return value of column b etc, in Oracle I'd do it like this (not tested on real table):

SELECT que, decode(ans, 'A', a, 'B', b, 'C', c, 'D', d, 'No answer') FROM question

Pawel

Try like this

select que,
  switch(
    ans = 'A', A
  , ans = 'B', B
  , ans = 'C', C
  , ans = 'D', D
  )
from table1

OR

   select que, IIf(ans='A', A, IIf(ans='B',B,IIf(ans='C',C,D))) from table1

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