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
264 views
in Technique[技术] by (71.8m points)

sql - Comparing 2 vaues in the same table based on criteria from a different table

What I want is to retrieve all ID''s Where the corresponding value of a color is higher then the corresponding value from a different color.
For example, I want where Value of 'Blue' is larger then the Value of 'Purple' Where the ID's match.

I have the following tables:
Table1

ID  |   Color   |   KeyA    |   KeyB
1   |   Blue    |   AB      |   13
1   |   Green   |   AC      |   15
1   |   Purple  |   AG      |   56
2   |   Purple  |   DF      |   46
2   |   Pink    |   GH      |   67
3   |   Orange  |   GH      |   89
3   |   Green   |   YU      |   97

Table2

KeyA    |   KeyB    |   Value       
AB      |   13      |   55      
DF      |   46      |   34      
YU      |   97      |   56      
DF      |   46      |   23      
AG      |   56      |   34      

IN this example the result will be 1

Only the used Values:

Table1

ID  |   Color   |   KeyA    |   KeyB
1   |   Blue    |   AB      |   13
1   |   Purple  |   AG      |   56

Table2

KeyA    |   KeyB    |   Value       
AB      |   13      |   55      
AG      |   56      |   34      
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

In this case you should use two time the t2 table .. should be

select t1.ID 
from table1 t1 
inner join t12 on t1.color = 'Blue'  and t12.color ='Purple'
inner join  Table2 t2 ON t1.KeyA = t2.KeyA AND t1.KeyB = t2.KeyB 
inner join  Table2 t22 ON t1.KeyA = t22.KeyA AND t12.KeyB = t22.KeyB 
WHERE  t2.value > t22.value 

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

...