简体   繁体   中英

Get the mostly occured value in multiple columns of a table

I have table which contains three columns Work, Cost, Duration. I need to get the maximum occurred values in all three columns. If two values occurred same times, then return the maximum value from that two. Please see the sample data & result below.

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

I need to get the result as

Work    Cost    Duration
 6       2         7

I tried with the following query, But it is returning the value for one column, that too it is returning the count for all the values

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

You can do something like

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)

Try the following:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM