简体   繁体   English

SQL - 基于最大列数返回 coumn 值

[英]SQL - return coumn value based on max column count

I have an SQL query where I can look up the maximum occurrence of a column.我有一个 SQL 查询,我可以在其中查找列的最大出现次数。 It works fine for what I needed, but now need to expand on this to only return the name of the column.它可以很好地满足我的需要,但现在需要对此进行扩展以仅返回列的名称。

There's likely a way to improve my original query but I haven't been able to work it out.可能有一种方法可以改进我的原始查询,但我一直无法解决。

select COMMUNITY_AREA_NUMBER, count(*) as CRIMES
    from CHICAGO_CRIME_DATA
    group by COMMUNITY_AREA_NUMBER
    order by CRIMES desc
    limit 1

My basic question is, how can I re-write this to only return the COMMUNITY_AREA_NUMBER?我的基本问题是,如何重写它以仅返回 COMMUNITY_AREA_NUMBER?

I've tried to restructure as:我试图重组为:

select COMMUNITY_AREA_NUMBER from CHICAGO_CRIME_DATA
    where count(*) as CRIMES group by COMMUNITY_AREA_NUMBER order by CRIMES desc limit 1

I've also tried to incorporate a MAX function, but I don't seem to be getting anywhere with it.我也试过合并一个 MAX function,但我似乎没有得到任何结果。

edit: Apparently I've just learned something inner queries.编辑:显然我刚刚学到了一些内部查询。 I needed to keep my original query and create an outer query that request something from that result.我需要保留我的原始查询并创建一个从该结果中请求某些内容的外部查询。

select COMMUNITY_AREA_NUMBER from
    (select COMMUNITY_AREA_NUMBER, count(*) as CRIMES
    from CHICAGO_CRIME_DATA
group by COMMUNITY_AREA_NUMBER
order by CRIMES desc
limit 1)

Is this what you want?这是你想要的吗?

SELECT COMMUNITY_AREA_NUMBER
FROM CHICAGO_CRIME_DATA
GROUP BY COMMUNITY_AREA_NUMBER
ORDER BY COUNT(*) DESC
LIMIT 1;

This returns a single community number having the most crime records.这将返回具有最多犯罪记录的单个社区号码。 I have simply moved COUNT(*) from the select clause, where you don't want it, to the ORDER BY clause.我只是将COUNT(*)从您不需要的 select 子句移动到ORDER BY子句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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