最常见的观察或集合的中位数

时间:2013-06-12 19:04:19

标签: sql-server-2008

我正在汇总数据而我无法对某些列求和,所以我想从该列中最频繁地观察或中值。示例如下,先谢谢。

ID网站

1 3

1 3

1 2

1 3

2 4

2 5

2 5

2 5

我希望它看起来像

ID网站

1 3

2 5

1 个答案:

答案 0 :(得分:0)

WITH temp AS(
  SELECT ID, Site, COUNT(*) As counts
  FROM id_table 
  GROUP BY ID, Site
)
SELECT temp.ID, temp.Site
FROM temp
JOIN (SELECT ID, MAX(counts) max_counts
      FROM temp 
      GROUP BY ID
     )b
ON temp.ID = b.ID
AND temp.counts = b.max_counts
ORDER BY ID ASC

SQL Fiddle