sqlite从两个表中选择最小值和最大值

时间:2013-11-09 20:51:29

标签: sqlite max min

我有两张桌子

表1

c1t1    c2t1
1       saanu
3       abc

表2

c1t2    c2t2
2       val2
4       val4

我必须用一行命令找出c2t1和c2t2的最小值和最大值c2t1和c2t2的值。

对于上面的例子,我必须找到saanu和val4

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

1)

SELECT c2t1
FROM table1
ORDER BY c1t1 ASC LIMIT 1

2)

SELECT c2t2
FROM talbe2
ORDER BY c1t2 DESC LIMIT 1

答案 2 :(得分:0)

我有一个非常类似的问题并用UNION ALL解决了。表aTable1,...,aTableN中aColumn列的最小值可以计算为:

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

你应该能够在每个内部选择中做Min,但我还没有发现如何做到这一点!