如何在SQL中获得正确的加权平均日期

时间:2010-02-03 14:45:04

标签: sql sql-server sql-server-2005 tsql

我使用此查询来获取我的平均日期:

CONVERT(DATETIME, AVG(CONVERT(FLOAT, ChargeOffDate))) as [Average C/O Date]

这正确地给了我'2003-08-12 14:17:22.103'的日期。

当我使用此查询获取加权平均日期

CONVERT(DATETIME, SUM(CONVERT(FLOAT, ChargeOffDate) * FaceValue) / SUM(FaceValue))

我得到的日期类似于'1938-10-19 21:28:48.000',这与平均日期不同。我觉得这是一件简单的事情,我错过了一些关键而且很小的东西。

示例:

declare @temp table (value datetime, [weight] money)
insert into @temp values (NULL,8850.00)
insert into @temp values (NULL,137.91)
insert into @temp values ('2006-01-15',221.13)
insert into @temp values ('2006-10-15',127.40)
insert into @temp values ('2001-07-31',551.44)
insert into @temp values ('1997-10-12',4963.41)
insert into @temp values ('2006-03-15',130.36)
insert into @temp values ('2005-01-07',1306.31)

SELECT
    CONVERT(DATETIME, AVG(CONVERT(FLOAT, value))) as [Avg Date],
    CONVERT(DATETIME, SUM(CONVERT(FLOAT, value) * [weight]) / SUM([weight])) as [Weighted Avg Date]
FROM @temp

这将'2003-11-25 20:00:00.000'作为平均日期,并将'1944-10-13 10:52:10.573'作为加权平均值。没有空值,它给出'1999-12-02 17:10:51.087'。我的问题可能是空值丢失了我的计算。

1 个答案:

答案 0 :(得分:2)

最有可能的是,ChargeOffDate的某些NULLFaceValues,但WITH q (ChargeOffDate, FaceValue) AS ( SELECT CAST('20030101' AS DATETIME), 1.0 UNION ALL SELECT CAST('20030201' AS DATETIME), 2.0 UNION ALL SELECT CAST('20030301' AS DATETIME), 3.0 UNION ALL SELECT NULL, 4.0 ) SELECT CONVERT(DATETIME, SUM(CONVERT(FLOAT, ChargeOffDate) * FaceValue) / SUM(FaceValue)) FROM q ---- 1961-11-12 21:36:00.000 不是。{/ p>

这些记录对第一笔金额没有贡献,但对第二笔金额有贡献。

WITH    q (ChargeOffDate, FaceValue) AS
        (
        SELECT  CAST('20030101' AS DATETIME), 1.0
        UNION ALL
        SELECT  CAST('20030201' AS DATETIME), 2.0
        UNION ALL
        SELECT  CAST('20030301' AS DATETIME), 3.0
        UNION ALL
        SELECT  NULL, 4.0
        )
SELECT  CONVERT(DATETIME, SUM(CONVERT(FLOAT, ChargeOffDate) * FaceValue) / SUM(FaceValue))
FROM    q
WHERE   ChargeOffDate IS NOT NULL

----
2003-02-09 20:00:00.000

使用此:

{{1}}