2013-11-09 67 views
0

我有兩個表sqlite的選擇最小和最大的兩個表

table1的

c1t1 c2t1 
1  saanu 
3  abc 

表2

c1t2 c2t2 
2  val2 
4  val4 

我必須找出c2t1和c2t2爲最低值,並一行命令的c1t1和c1t2的最大值。

對於上面的例子中我要找到saanu和VAL4

回答

1

一種方法:

select max(case c1 when min1 then c2 end) c2_first, 
     max(case c1 when max1 then c2 end) c2_last 
from (select c1t1 c1, c2t1 c2 from table1 
     union all 
     select c1t2 c1, c2t2 c2 from table2) u 
cross join 
(select min(min11, min12) min1, max(max11, max12) max1 from 
(select min(c1t1) min11, max(c1t1) max11 from table1) t1 
cross join 
(select min(c1t2) min12, max(c1t2) max12 from table2) t2) m 

SQLFiddle here

0

1)

SELECT c2t1 
FROM table1 
ORDER BY c1t1 ASC LIMIT 1 

2)

SELECT c2t2 
FROM talbe2 
ORDER BY c1t2 DESC LIMIT 1 
+0

對不起,我沒有提到,我想要它與一條線commant – kosbou

0

我有一個非常類似的問題,並用UNION ALL解決了它。在表中的將aColumn列的最小aTable1,...,aTableN可以計算爲:

SELECT Min(aColumn) 
FROM (
SELECT aColumn FROM aTable1 UNION ALL 
SELECT aColumn FROM aTable2 UNION ALL 
... 
SELECT aColumn FROM aTableN) t; 

你應該能夠做到民在每個內選擇,但我還沒有找到如何去做!