T-SQL查询 - 聚合

时间:2017-06-15 17:06:51

标签: sql sql-server

使用SQL Server 2016.我有以下示例数据:

    Date      Total_Req.    Changed     Deleted     New
    9/16/2008   271            7          1          3
    10/14/2008  235            1         10         11
    10/15/2008  131            2          3          5
    11/21/2009  190            4          5          2
    11/22/2009  125            5         12          1
    11/23/2009  181            6          1          4
    4/13/2011   300            8          2          8
    4/26/2011   281            11         7          9
    4/26/2011   302             5         8         10

我可以使用以下内容轻松地每月汇总:

    Select cast(Format([Date], 'MM/01/yyyy') as date) as [Date], 
    SUM([Changed]) as [Changed], SUM([Deleted]) as [Deleted], SUM([New]) as 
    [New] GRPUP BY Format([Date], 'MM/01/yyyy')

到目前为止这么好,我按月得到一笔钱:

    Date        Changed Deleted New
    9/1/2008    7          1    3
    10/1/2008   3         13    16
    11/1/2009   15        18    7
    4/1/2011    19         9    17

但是,我需要在查询中包含 Total_Req的值一个月中的最后一个日期 ,因此所需的输出将为:

    Date    Total Req.  Changed Deleted New
    9/1/2008    271        7     1      3
    10/1/2008   131        3     13    16
    11/1/2009   181       15    18      7
    4/1/2011    302       19    9      17

我怎样才能做到这一点?

谢谢, M.R。

2 个答案:

答案 0 :(得分:1)

只需在Total Req列中使用相关子查询,选择外部查询中行的月份的日期为MAX(日期)的总Req。 (或使用TOP 1在子查询中按日期DESC排序)。

答案 1 :(得分:1)

只需将子查询从SELECT子句运行回原始表回到原始表:

SELECT cast(Format([Date], 'MM/01/yyyy') as date) as [Date],
    (SELECT TOP 1 [Total_Req.] FROM [MyTable] t0 WHERE Format(t0.[Date], 'MM/01/yyyy') = Format(t.[Date], 'MM/01/yyyy') ORDER BY t0.[Date] DESC) as [Total_Req.],
    SUM([Changed]) as [Changed], SUM([Deleted]) as [Deleted], SUM([New]) as [New] 
FROM [MyTable] t
GROUP BY Format([Date], 'MM/01/yyyy')

SELECT cast(Format([Date], 'MM/01/yyyy') as date) as [Date],
    MIN(t1.[Total_Req.]) As [Total_Req.],
    SUM([Changed]) as [Changed], SUM([Deleted]) as [Deleted], SUM([New]) as [New] 
FROM [MyTable] t
CROSS APPLY (SELECT TOP 1 [Total_Req.] FROM [MyTable] t0 WHERE Format(t0.[Date], 'MM/01/yyyy') = Format(t.[Date], 'MM/01/yyyy') ORDER BY t0.[Date] DESC) t1
GROUP BY Format([Date], 'MM/01/yyyy')

如果您确实需要更快的结果,请查看FORMAT([Date], 'MM/01/yyyy')表达式。此表达式切入此查询的核心,因为它以三种不同的方式使用,包括子查询或APPLY的匹配条件。表达式也不可攻击,这意味着无论您使用哪种索引,它们都无法帮助您处理需要此值的查询元素。

如果您为此表达式的表添加计算列,则可以在索引中使用新列,并且您应该更多更快的结果。