简体   繁体   English

如何在SQL中获得MAX(COUNT)?

[英]How to get MAX(COUNT) in SQL?

I would like to get the name of the entity which has MAX count in the dataset and would also like to get the count of the same. 我想获取在数据集中具有MAX计数的实体的名称,也想获取相同的计数。

SELECT 
    STORE_TYPE AS 'FREQUENT CHANNEL', 
    COUNT(STORE_TYPE) AS 'TOTAL TRANSACTIONS'
FROM 
    TRANSACTION_INFO
GROUP BY 
    STORE_TYPE

This returns the count of the STORE_TYPE along with the TOTAL_TRANSACTIONS . 这将返回STORE_TYPE的计数以及TOTAL_TRANSACTIONS

Now, I would like to fetch the STORE_TYPE along with TOTAL TRANSACTIONS which has performed the best (MAX). 现在,我想获取 STORE_TYPE以及表现最佳(MAX)的TOTAL TRANSACTIONS

Thanks in advance! 提前致谢!

If you want one row, the logic would be group by to calculate the count. 如果需要一行,则将逻辑group by以计算计数。 Then order by and some way of limiting the result to the top: 然后order by并以某种方式将结果限制在顶部:

SELECT STORE_TYPE, COUNT(*) AS cnt
FROM TRANSACTION_INFO
GROUP BY STORE_TYPE
ORDER BY cnt DESC
FETCH FIRST 1 ROW ONLY;

In the event of ties, this only returns one arbitrary row with the highest value. 在平局的情况下,这仅返回一个具有最高值的任意行。 The best way to handle ties depends on the database. 处理联系的最佳方法取决于数据库。

FETCH FIRST 1 ROW ONLY is the ISO/ANSI standard for limiting the result set to one row. FETCH FIRST 1 ROW ONLY是ISO / ANSI标准,用于将结果集限制为一行。 Your database may use a different syntax for this. 您的数据库可能为此使用不同的语法。

I also strongly discourage you from using single quotes for column aliases. 我也强烈建议您不要对列别名使用单引号。 Use names that don't need to be escaped -- that is the best advise. 使用不需要转义的名称-这是最好的建议。 Otherwise, use the escape mechanism for your database, typically double quotes, backticks, or square braces. 否则,请对数据库使用转义机制,通常使用双引号,反引号或方括号。

EDIT: 编辑:

The solution in SQL Server that includes ties is: SQL Server中包含联系的解决方案是:

SELECT TOP (1) STORE_TYPE, COUNT(*) AS cnt
FROM TRANSACTION_INFO
GROUP BY STORE_TYPE
ORDER BY cnt DESC;

If you only want one row, remove the WITH TIES . 如果只需要一行,则删除WITH TIES

You can simply ORDER BY the max and then limit to a single row. 您可以简单地最大订购,然后限制为单行。

SELECT 
STORE_TYPE AS 'FREQUENT CHANNEL', 
COUNT(STORE_TYPE) AS 'TOTAL TRANSACTIONS'
FROM TRANSACTION_INFO
GROUP BY STORE_TYPE
ORDER BY 'TOTAL TRANSACTIONS' DESC
LIMIT 1

The way to LIMIT depends on the SQL dialect. LIMIT的方式取决于SQL方言。

The other answers work well, as long as there's a single store_type that is doing best. 只要有一个最佳的store_type ,其他答案就可以很好地工作。 If you also want to account for multiple ones tied in first place you should use: 如果您还想考虑多个并列第一的位置,则应使用:

with s (t, c) as (
  select store_type, count(*)
    from transaction_info group by store_type
)
select
    t as 'FREQUENT CHANNEL',
    c as 'TOTAL TRANSACTIONS'
  from s
  where c = (select max(c) from s)

This query will show you one or more rows. 此查询将向您显示一个或多个行。

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

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