简体   繁体   English

SQL服务器中的查找模式

[英]Finding mode in SQL Server

I have the below query which returns me the mode which is the most repeated value in a data set我有以下查询,它返回给我的模式是数据集中重复次数最多的值

select top 1 TargetPriceRec as mode 
from PricingRecurring  
Group By TargetPriceRec order by Count(*) desc

I get the most repeated value from this but the issue is that if there is no repeated value I am still getting the highest value in the dataset.我从中获得了最多重复的值,但问题是如果没有重复值,我仍然会在数据集中获得最高值。 How can I get an empty value if there are no repeating values in the dataset and also if there are multiple repeating values I still get an empty value since there is no single mode.如果数据集中没有重复值,并且如果有多个重复值,我如何获得一个空值,因为没有单一模式,我仍然会得到一个空值。

Any help is much appreaciated.任何帮助都非常感谢。

Thanks谢谢

You can get all the modes using:您可以使用以下方式获取所有模式:

select top (1) with ties TargetPriceRec as mode 
from PricingRecurring  
Group By TargetPriceRec
order by Count(*) desc;

For your desired results:为了您想要的结果:

select (case when count(*) = 1 then max(TargetPriceRec) end) as mode
from (select top (1) with ties TargetPriceRec 
      from PricingRecurring  
      Group By TargetPriceRec
      order by Count(*) desc
     ) m

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

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