【问题标题】:SQL Calculations for budgeting用于预算的 SQL 计算
【发布时间】:2016-09-01 21:05:46
【问题描述】:

我有一个包含以下列的数据库: 供应商、金额、开始日期、月份

我希望能够根据输入的月份计算平均每月金额。我还希望看到它根据 StartDate + Months 计算从开始日期计算到结束日期。结果表如下所示:

Vendor1 从 1 月 1 日开始有 2 个月的 1112,而 Vendor2 从 2 月 1 日开始有 3 个月的 2040

|       | ANNUAL | JAN   |  FEB  |  MAR  | APR   | 
Vendor1 |  2,224 | 1,112 | 1,112 |       |       |
Vendor2 |  6,120 |       | 2,040 | 2,040 | 2,040 | 

任何帮助或指导将不胜感激。

【问题讨论】:

  • 我删除了不兼容的数据库标签。随意为您正在使用的数据库添加标签。

标签: sql pivot calculated-columns


【解决方案1】:

这是一个奇怪的数据库设计。但是,您必须尝试以下方法:

SELECT (Amount * Months) AS Annual, (Case @(StartDate < DATE("01.02.year")) WHEN 1 THEN Amount ELSE NULL) AS Jan FROM Table --etc for all months

虽然会考虑修改,因为这种方式有点太简单了。

【讨论】:

    【解决方案2】:

    您将使用条件聚合。假设开始日期都在同一年,代码可能如下所示:

    select vendorid, (amount * months) as total,
           (case when month(startdate) <= 1 and month(startdate) + months >= 1
                 then amount
            end) as jan,
           (case when month(startdate) <= 2 and month(startdate) + months >= 2
                 then amount
            end) as feb,
           (case when month(startdate) <= 3 and month(startdate) + months >= 3
                 then amount
            end) as mar,
           (case when month(startdate) <= 4 and month(startdate) + months >= 4
                 then amount
            end) as apr,
    from t;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多