SQL:在第1列中查找特定成员的最常见值

时间:2016-04-06 15:30:07

标签: sql

我有以下SQL相关问题:

我们假设我有以下简单的数据表:

enter image description here

我想确定最常见的街道地址,并将其放在第3栏:

enter image description here

我认为使用COUNT这应该是相当简单的?不太确定如何去做。非常感谢任何帮助

此致

4 个答案:

答案 0 :(得分:2)

这是我刚写的一个很长的方法。它只列出最常用的地址。您必须获取这些值并将它们插入表中。看看它是否适合你:

select * from

(select d.company, count(d.address) as final, c.maxcount,d.address
from dbo.test d inner join

(select a.company,max(a.add_count) as maxcount from

(select company,address,count(address) as add_count  from dbo.test group by company,address)a


group by a.company) c
on (d.company = c.company)



group by d.company,c.maxcount,d.address)e
where e.maxcount=e.final

答案 1 :(得分:1)

这是标准SQL中的查询。它首先计算每个公司和地址的记录,然后按公司排名,给出最常出现的地址等级#1。然后它只保留那些排名最好的地址记录,再次与表格连接并显示结果。

select
  mytable.company,
  mytable.address,
  ranked.address as most_common_address
from mytable 
join
(
  select
    company,
    address,
    row_number() over (partition by company oder by cnt desc) as rn
  from
  (
    select
      company,
      address,
      count(*) over (partition by company, address) as cnt
    from mytable
  ) counted
) ranked on ranked.rn = 1
         and ranked.company = mytable.company
         and ranked.address = mytable.address;

答案 2 :(得分:0)

此select语句将为您提供最频繁的事件。 我们称之为

SELECT       `value`,
         COUNT(`value`) AS `value_occurrence` 
    FROM     `my_table`
    GROUP BY `value`
    ORDER BY `value_occurrence` DESC
    LIMIT    1;

INSERT 添加到您的表格中

INSERT INTO db (col1, col2, col3) VALUES (val1, val2, A)

请注意,您需要A!

的整个选择陈述

答案 3 :(得分:0)

你没有提到你的DBMS。这是Oracle的解决方案。

select
  company,
  address,
  (
    select stats_mode(address) 
    from mytable this_company_only
    where this_company_only.company = mytable.company
  ) as most_common_address
from mytable;

这看起来有点笨拙,因为STATS_MODE仅作为聚合函数使用,而不是作为分析窗函数。