如何使用均值,中位数和众数创建新的SQL表?

时间:2018-10-22 13:20:31

标签: sql mean median mode

好吧,所以我是SQL的新手,这就是为什么我问这个问题。

我有一个表,名为: kpi_notification_metrics_per_month 该表有2列:

  • 日期
  • NotificationCount

我想创建一个将显示的全新表格

  • 平均值
  • 中位数
  • 模式

对于NotificationCount列。

示例表:

Date    NotificationCount
01/04/2018 00:00    0
31/03/2018 00:00    0
25/03/2018 00:00    0
24/03/2018 00:00    0
22/03/2018 00:00    0
18/03/2018 00:00    0
17/03/2018 00:00    0
14/03/2018 00:00    0
11/03/2018 00:00    0
07/04/2018 00:00    1
26/03/2018 00:00    1
21/03/2018 00:00    1
15/03/2018 00:00    1
13/03/2018 00:00    1
12/03/2018 00:00    1
10/03/2018 00:00    1
08/04/2018 00:00    2
30/03/2018 00:00    2
09/03/2018 00:00    2
08/03/2018 00:00    2
20/03/2018 00:00    3
19/03/2018 00:00    4
02/04/2018 00:00    9
23/03/2018 00:00    11
27/03/2018 00:00    22
03/04/2018 00:00    28
28/03/2018 00:00    34
04/04/2018 00:00    39
05/04/2018 00:00    43
29/03/2018 00:00    47
06/04/2018 00:00    50
16/03/2018 00:00    140

预期结果:

Mean    Median  Mode
13.90625    1   0

2 个答案:

答案 0 :(得分:0)

平均值:使用Avg()

Select Avg(NotificationCount)
From   kpi_notification_metrics_per_month

中位数:按ASC和DESC对TOP 50 Percent的数据进行排序,找到中间的数据。

Select ((
        Select Top 1 NotificationCount
        From   (
                Select  Top 50 Percent NotificationCount
                From    kpi_notification_metrics_per_month
                Where   NotificationCount Is NOT NULL
                Order By NotificationCount
                ) As A
        Order By NotificationCountDESC) + 
        (
        Select Top 1 NotificationCount
        From   (
                Select  Top 50 Percent NotificationCount
                From    kpi_notification_metrics_per_month
                Where   NotificationCount Is NOT NULL
                Order By NotificationCount DESC
                ) As A
        Order By NotificationCount Asc)) / 2

模式:获取每个值集的计数并以DESC顺序获取前1行。

SELECT TOP 1 with ties NotificationCount
FROM   kpi_notification_metrics_per_month
WHERE  NotificationCount IS Not NULL
GROUP  BY NotificationCount
ORDER  BY COUNT(*) DESC

所有工作在Sql Server 2014中。

参考:http://blogs.lessthandot.com/index.php/datamgmt/datadesign/calculating-mean-median-and-mode-with-sq/

答案 1 :(得分:0)

这是在Oracle中执行此操作的方法:

var configOptions = new StackExchange.Redis.ConfigurationOptions
{
   ConnectTimeout = 5000,
   ConnectRetry = 5,
   SyncTimeout = 5000,
   AbortOnConnectFail = false,
};

configOptions.EndPoints.Add(host, port);

var conn = StackExchange.Redis.ConnectionMultiplexer.Connect(configOptions);
return conn;

不需要另一个表。您可以(并且应该)始终临时查询数据。为了方便起见,您可以按照jarlh在请求注释中建议的方式创建视图。