查找大于平均金额的金额

问题描述 投票:0回答:2

应付下放管理部门的学生贷款偿还 - 其他应付款项 138442925 33167682.1339252 支付给HMT的现金CFER 139584240.89 33167682.1339252 当前对私营部门的赠款 - NPISH 707862504.75 33167682.1339252 向私营部门提供资本补助 - 公司 45186124.85 33167682.1339252 新增贷款-助学贷款 1348364678 33167682.1339252 向正常机构提供援助 2649997139.35 33167682.1339252 添加 - 其他贷款 - 上市公司 1847000000 33167682.1339252

sql sql-server sql-server-2008
2个回答
1
投票

您可以使用窗口函数

AVG(...) OVER ()
来平均表中的所有值。

SELECT
 *
FROM (
    SELECT
      ExpenseType,
      SUM(Amount) AS avgvalue,
      AVG(SUM(Amount)) OVER () AS average
    FROM mydatatable
    WHERE DATEPART(month, DateofPayment) BETWEEN 4 AND 9 
    GROUP BY ExpenseType
) z
WHERE avgvalue > average

0
投票

如果这是 SQL Server 2022,我建议使用

DATE_BUCKET()
函数将源日期干净地映射到 6 个月的buckets

对于早期版本的 SQL Server,您可以使用以下计算:

DATEADD(
    month,
    DATEDIFF(month, '1900-04-01', DateOfPayment ) / 6 * 6,
    '1900-04-01'
    ) AS DateBucket

这里,

'1900-04-01'
是用于定义任意6个月窗口(桶)开始的参考日期。
/ 6 * 6
用于将月份数字向下舍入为之前 6 个月的倍数。

然后可以将其包装在

CROSS APPLY
中,并在以后的
GROUP BY
或窗口函数
PARTITION BY
条件中使用。

生成的查询类似于:

select
    DateBucket as FromDate,
    dateadd(day, -1, dateadd(month, 6, DateBucket)) as ThruDate,
    Expense_Type,
    SumAmount,
    AvgSumAmount
from (
    select
        DateBucket,
        Expense_Type,
        sum(Amount) as SumAmount,
        avg(sum(Amount)) OVER(PARTITION BY DateBucket) AS AvgSumAmount
    from ExpenseTable E
    cross apply (
        select dateadd(
            month, 
            datediff(month, '1900-04-01', Date_Of_Payment ) / 6 * 6,
            '1900-04-01'
            ) AS DateBucket
    ) b
    group by DateBucket, Expense_Type
) a
where SumAmount > AvgSumAmount
order by DateBucket, Expense_Type;

内部查询计算 6 个月的日期桶,然后按日期桶和费用类型对费用数据进行分组,并在此过程中对金额进行求和。它还使用窗口函数计算每个日期存储桶的平均总费用。然后,顶层仅对结果应用最终过滤条件。

结果:

起始日期 截止日期 费用_类型 金额 平均总金额
2022-04-01 2022-09-30 顾问开支 14499.50 3166.166666
2022-10-01 2023-03-31 刑法 28500.50 12500.666666
2023-04-01 2023-09-30 刑法 18500.00 4000.250000
2023-10-01 2024-03-31 刑法 23000.50 12333.750000

请参阅 this db<>fiddlethis one 进行演示。

© www.soinside.com 2019 - 2024. All rights reserved.