-2

我有一个查询,它返回一组记录,如下所示:-

Date    Dept        commission

5-Apr   Sales       20
4-Apr   Sales       21
1-Jan   Marketing   35

案例 1:如果我在 1 月 1 日到 4 月 5 日之间运行查询,我应该得到

Date    Dept        commission

5 April Sales       76

案例 2:当我在 1 月 1 日和 1 月 31 日之间运行查询时,应该得到输出为

Date    Dept        commission

1 Jan   Marketing   35

案例 2 很简单,因为我将日期范围设置为所需的结果,但不确定如何处理案例 1 以显示最大/最新日期、该日期的部门以及该部门的佣金总和、日期选定的日期范围。输出将是具有最新日期和部门的单行,其中包含所选日期范围的总和(佣金)。

4

1 回答 1

3
SELECT
    MAX(Date)                     AS Date
  , ( SELECT tt.Dept                            
      FROM tableX tt 
      WHERE tt.Date = MAX(t.Date) 
    )                             AS Dept
  , SUM(Commission)               AS Commission
FROM
    tableX t
WHERE
    Date BETWEEN StartDate AND EndDate

如sql-fiddle、test-1所示,上述内容在 SQL-Server、MySQL、Postgres 中有效,但在 Oracle 11g R2 中无效!


这虽然有效(sql-fiddle, test-2):

SELECT
    MAX(t.Date)        AS Date
  , MIN(tt.Dept)       AS Dept               --- MIN, MAX irrelevant
  , SUM(t.Commission)  AS Commission
FROM
  ( SELECT
       MAX(Date)                      AS Date
     , SUM(Commission)                AS Commission
    FROM
       tableX 
    WHERE
       Date BETWEEN StartDate AND EndDate
  ) t
  JOIN
    tableX tt
      ON tt.Date = t.Date

MIN(tt.Dept)用于处理您有超过最大日期的行的情况,例如一排和Sales一排Marketing,两者都在Apr-5

这也可以使用LAST_VALUE分析函数(sql-fiddle, test-3):

SELECT
    MAX(Date)        AS Date
  , MIN(Dept)        AS Dept               
  , SUM(Commission)  AS Commission
FROM
  ( SELECT
       Date                      AS Date
     , LAST_VALUE(Dept) OVER( ORDER BY Date
               ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING 
                            )    AS Dept
     , Commission                AS Commission
    FROM
       tableX 
    WHERE
       Date BETWEEN StartDate AND EndDate
  ) t
于 2012-04-08T07:44:51.073 回答