我有一张桌子,我每分钟都会计算使用过的许可证。 cron任务检查会话面板并计算每分钟的会话数。它填充session_counts
表。
Session_counts
:
CREATE TABLE [dbo].[session_counts](
[id] [int] IDENTITY(1,1) NOT NULL,
[license_count] [int] NOT NULL,
[created_at] [datetime] NOT NULL,
[updated_at] [datetime] NOT NULL,
PRIMARY KEY CLUSTERED
(
[id] ASC
)
示例值(我的真实数据表中一年有525600行):
id license_count created_at updated_at
1 879 2014-12-30 15:58:42.000 2014-12-30 16:10:50.000
2 55 2014-05-28 12:20:00.000 2014-05-28 12:26:45.000
3 40 2014-03-15 15:51:26.000 2014-03-15 16:02:29.000
4 979 2014-04-25 09:09:49.000 2014-04-25 09:24:03.000
5 614 2014-12-27 11:17:53.000 2014-12-27 11:19:36.000
6 721 2014-09-02 15:20:40.000 2014-09-02 15:32:47.000
7 625 2014-02-27 11:17:42.000 2014-02-27 11:23:26.000
8 1576 2014-12-30 17:18:32.000 2014-12-30 17:36:55.000
9 893 2014-07-26 17:32:47.000 2014-07-26 17:34:22.000
10 897 2014-07-19 11:26:32.000 2014-07-19 11:42:26.000
现在我想在这样的时间范围之间创建统计数据:
SELECT
MIN(license_count) min_lic
, MAX(license_count) max_lic
, AVG(license_count) avg_lic
, DATEPART(month, created_at) monat
FROM session_counts
WHERE created_at BETWEEN '01.01.2014' AND '31.12.2014'
GROUP BY DATEPART(month, created_at)
ORDER BY monat DESC
这为我提供了MIN
,AVG
,MAX
用法。
而不是AVG
我希望得到许可证使用的中间值。
我的目的是在一年内切断最小/最大峰值,以获得更实际的使用统计数据。如果有必要,我可以设置最小/最大间隙值,如果有帮助的话。
我之前检查了此链接Function to Calculate Median in Sql Server,但我无法将其转换为我的需要。
我需要在SQL Server 2005,2008和2012上进行此操作,因此我无法在2012年使用PERCENTILE_CONT()
。
如果有人想创建一个表并填充大量数据,我可以提供这个小的TSQL来填充数据:
DECLARE @numRows int,@i int, @date datetime
SET @numRows = 100000
SET @i=1
WHILE @i<@numRows
BEGIN
SET @date = DATEADD(second, RAND()*36000, DATEADD(day, RAND()*365, '2014-01-01 08:00:00'))
INSERT session_counts (license_count, created_at, updated_at)
SELECT CAST(RAND()*1000 AS int) license_count
, @date created_at
, DATEADD(second, RAND()*1440, @date) updated_at
SET @i=@i+1
END
希望有人能解决我的问题。
答案 0 :(得分:1)
试图实现此处描述的方法:http://www.sqlperformance.com/2012/08/t-sql-queries/median
SELECT MIN(license_count) min_lic
, MAX(license_count) max_lic
, AVG(license_count) avg_lic
, SUM(CASE WHEN ra BETWEEN rd - 1 AND rd + 1 THEN license_count ELSE 0 END) * 1.0
/ SUM(CASE WHEN ra BETWEEN rd - 1 AND rd + 1 THEN 1 ELSE 0 END) as median_lic
, DATEPART(month, created_at) monat
FROM (
SELECT created_at
, license_count
, ROW_NUMBER() OVER (PARTITION BY DATEPART(month, created_at) ORDER BY license_count, created_at) as ra
, ROW_NUMBER() OVER (PARTITION BY DATEPART(month, created_at) ORDER BY license_count DESC, created_at DESC) as rd
FROM session_counts
WHERE created_at BETWEEN '01.01.2014' AND '31.12.2014'
) T
GROUP BY DATEPART(month, created_at)
ORDER BY monat DESC