获得与AVG TSQL函数最接近的值

时间:2018-09-12 19:34:50

标签: sql-server tsql

我有这样的选择:

SELECT
    FORMAT(AVG([DC].[ContractedAmount]) , '$###,###,###,###.##') AS [AverageContractedAmount]
FROM 
    [DesignCustomer] AS [DC]
INNER JOIN 
    [Design] AS [D] ON [DC].[DesignKey] = [D].[DesignKey]
INNER JOIN 
    [Task] AS [T] ON [D].[DesignKey] = [t].[DesignKey]
INNER JOIN 
    [ProjectDesign] AS [PD] ON [D].[DesignKey] = [PD].[DesignKey]
INNER JOIN 
    [Project] AS [P] ON [PD].[ProjectKey] = [P].[ProjectKey]
INNER JOIN 
    [Address] AS [A] ON [A].[AddressGuid] = [P].[ProjectGuid]

如您所见,我得到合同金额的Average。我得到这样的东西:

+---------------------------+
| [AverageContractedAmount] |
+---------------------------+
| $1,000.00                 |
+---------------------------+

现在我想找到最接近该值的项目

例如,如果我在项目表中有5个项目,例如:

+----------------+
|  ProjectName   |
+----------------+
| First Project  |
| Second Project |
| Third Project  |
| Four Project   |
| Five Project   |
+----------------+

[DC]与项目的关系如下:

+----------------+------------------+
|  ProjectName   | ContractedAmount |
+----------------+------------------+
| First Project  |              500 |
| Second Project |              700 |
| Third Project  |              300 |
| Four Project   |              950 |
| Five Project   |              800 |
+----------------+------------------+

我希望查询返回Four Project Name,因为它的ContractedAmount值最接近AVG值。我该如何实现?问候

2 个答案:

答案 0 :(得分:1)

您无需考虑太多,就可以将其转储到子查询中,然后减去,按差排序并保持最佳结果:

SELECT TOP 1
    project_name,

FROM Project
ORDER BY Abs(ContractedAmount - 
        (
            SELECT
            AVG([DC].[ContractedAmount]) AS [AverageContractedAmount]
             FROM [DesignCustomer] AS [DC]
                             INNER JOIN [Design] AS [D] ON [DC].[DesignKey] = [D].[DesignKey]
                             INNER JOIN [Task] AS [T] ON [D].[DesignKey] = [t].[DesignKey]
                             INNER JOIN [ProjectDesign] AS [PD] ON [D].[DesignKey] = [PD].[DesignKey]
                             INNER JOIN [Project] AS [P] ON [PD].[ProjectKey] = [P].[ProjectKey]
                             INNER JOIN [Address] AS [A] ON [A].[AddressGuid] = [P].[ProjectGuid]
        )) ASC

答案 1 :(得分:1)

似乎您已经想出了平均值,因此使用示例表,但又想获得平均值1000美元,我用平均值编写了一条select语句来获得答案。对于这个答案,我只是从表而不是您的代码中计算出平均值,以获得变量@AVERAGE。

    CREATE TABLE #Amts (Project VARCHAR(20), Amount INT);

    INSERT INTO #Amts 
    VALUES

    ('One Project', 500),
    ('Two Project', 1500),
    ('Three Project', 300),
    ('Four Project', 1700),
    ('Five Project', 1100),
    ('Six Project', 900)        ;

    DECLARE @AVERAGE INT = (SELECT AVG(Amount) FROM #Amts) -- $1000

    SELECT    TOP 1 Project -- Since you said whichever project is suitable, this should be fine. 
    FROM      #Amts AS A
    WHERE     ABS(A.Amount - @AVERAGE) = (SELECT MIN(ABS(Amin.Amount - @AVERAGE)) FROM #Amts AS Amin)
    ORDER BY  Project

    DROP TABLE #Amts

这将为您提供“五个项目”的答案。