获取表的多列中最常出现的值

时间:2013-07-25 09:11:29

标签: sql max

我的表包含三列工作,成本,持续时间。我需要获得最大值 所有三列中都出现了值。如果两个值同时出现,则返回 这两个的最大值。请参阅示例数据&结果如下。

Work    Cost      Duration
 5       2        6
 5       8        7
 6       8        7
 2       2        2
 6       2        6

我需要将结果作为

Work    Cost    Duration
 6       2         7

我尝试使用以下查询,但它返回一列的值,它也返回所有值的计数

select Duration, count(*) as "DurationCount" from SimulationResult
  group by Duration
  order by count(*) desc,Duration desc

2 个答案:

答案 0 :(得分:1)

您可以执行类似

的操作
select * from
(select top 1 Work from SimulationResult
  group by Work
  order by count(*) desc, Work desc),

(select top 1 Cost from SimulationResult
  group by Cost 
  order by count(*) desc, Cost desc),

(select top 1 Duration from SimulationResult
  group by Duration
  order by count(*) desc, Duration desc)

答案 1 :(得分:0)

尝试以下方法:

select max(t1.a), max(t2.b), max(t3.c)
from
(select a from (
select a, count(a) counta
from #tab
group by a) tempa
having counta = max(counta)) t1,
(select b from (
select b, count(b) countb
from #tab
group by b) tempb
having countb = max(countb)) t2,
(select c from (
select c, count(c) countc
from #tab
group by c) tempc
having countc = max(countc)) t3