TSQL总和行的日期小于每个不同日期的日期值

时间:2014-12-10 18:59:59

标签: sql-server tsql

我的表格结构如下:

CREATE TABLE [dbo].[vt](
[id] [uniqueidentifier] NOT NULL,
[ones] [money] NULL,
[twos] [money] NULL,
[fives] [money] NULL,
[tens] [money] NULL,
[twenties] [money] NULL,
[fifties] [money] NULL,
[hundreds] [money] NULL,
[ReportDate] [datetime] NULL)

如何编写查询以执行以下查询为每个不同的ReportDate执行的操作:

declare @date datetime
set @date = '11/3/2014';
SELECT 
ISNULL(SUM([ones]), 0) AS ones
,ISNULL(SUM([twos]), 0) AS twos
,ISNULL(SUM([fives]), 0) AS fives
,ISNULL(SUM([tens]), 0) AS tens
,ISNULL(SUM([twenties]), 0) AS twenties
,ISNULL(SUM([fifties]), 0) AS fifties
,ISNULL(SUM([hundreds]), 0) AS hundreds
,max(ReportDate) as ReportDate
FROM [vt]
WHERE 
ReportDate is not null and reportDate <= (@date)

2 个答案:

答案 0 :(得分:3)

您可以在报告日期&lt; =报告日期

内部将表连接到自身
SELECT  ISNULL(SUM(b.[ones]), 0) AS ones ,
        ISNULL(SUM(b.[twos]), 0) AS twos ,
        ISNULL(SUM(b.[fives]), 0) AS fives ,
        ISNULL(SUM(b.[tens]), 0) AS tens ,
        ISNULL(SUM(b.[twenties]), 0) AS twenties ,
        ISNULL(SUM(b.[fifties]), 0) AS fifties ,
        ISNULL(SUM(b.[hundreds]), 0) AS hundreds ,
        a.ReportDate
FROM    [vt] a
INNER JOIN [vt] b ON b.ReportDate <= a.ReportDate
WHERE   a.ReportDate IS NOT NULL
GROUP BY a.ReportDate

答案 1 :(得分:2)

您可以使用OUTER APPLY

;WITH Dates AS
(
    SELECT DISTINCT ReportDate
    FROM [vt]
)
SELECT *
FROM Dates A
OUTER APPLY (   SELECT  ISNULL(SUM([ones]), 0) AS ones,
                        ISNULL(SUM([twos]), 0) AS twos,
                        ISNULL(SUM([fives]), 0) AS fives,
                        ISNULL(SUM([tens]), 0) AS tens,
                        ISNULL(SUM([twenties]), 0) AS twenties,
                        ISNULL(SUM([fifties]), 0) AS fifties,
                        ISNULL(SUM([hundreds]), 0) AS hundreds,
                        MAX(ReportDate) as ReportDate
                FROM [vt]
                WHERE reportDate <= A.ReportDate) B