一个表中有a、b两种数据(可能更多种)
比如说表中
type, val, ps
-----------------------
a, 1, some text
b, 1, some text
a, 2, some text
b, 3, some text
a, 5, some text
查询a、b中数值各自最大项,得到查询结果
type, val, ps
---------------------
a, 5, some text
b, 3, some text
要求输出表中所有列(列数确定,而且已知)
---------------------------------------------------------------
select Type,Max(Val) as Val from TableName Group by Type
注意Select 與Group by 的用法,自己看下幫助
---------------------------------------------------------------
select type,max(val) from tablename group by type
---------------------------------------------------------------
问题是其他列怎么取值呢?
---------------------------------------------------------------
select type, max(val)
from tablename
group by type
order by type
---------------------------------------------------------------
如果是随意取值的话:
select t.*,m.maxVal from (select distinct * from tbName group by type) t INNER JOIN (select type,max(val) as maxVal from tbName group by type) m ON t.type=m.type
---------------------------------------------------------------
這樣應該可以
select tb1.*
from tablename tb1 inner join
(select Type,Max(Val) from tablename group by Type) tb2 on
tb1.type=tb2.type and tb1.val=tb2.val
---------------------------------------------------------------
可能是我说得不够清楚,真正理解我的想法的是 dotAge(老朽,提醒你及时结贴) 和 yohar(一飄仙) 两位。
我的表中除了这两列以外还有其他列的。
表中的结构比如为
t, v, ps
--------------------
a, 1, sometext
b, 1, sometext
a, 2, sometext
对于两位的解法,dotAge(老朽,提醒你及时结贴)的解法是有问题的。
select t.*,m.maxVal
from (select distinct * from abc group by t) t INNER JOIN (select t,max(v) as maxVal from abc group by t) m ON t.t=m.t
系统提示 abc.v,abc.ps 没有包含在聚合函数里面。
对于 yohar(一飄仙) 的解法,是可行的,只是有一点点小瑕疵,要修改一下
select tb1.*
from abc tb1 inner join
(select t,Max(v) AS v from abc group by t) tb2 on
...........^^^^^^^^^^......
tb1.t=tb2.t and tb1.v=tb2.v
否则系统要提示tb2的第二列没有定义。
谢谢各位高手的解答。这个问题烦了我一天了,呵呵。