0

我正在尝试为一系列不同的标准进行选择。我基本上要取今天的日期,并将其用于我们的发票表,以了解与过去几年相比,我们今年的情况如何。

最后,我基本上想要有年份、年初至今销售额、季度至今销售额和月至今销售额的列。我已经开始为此创建一个循环,但我遇到的问题是它正在执行几个选择,而不是返回一个数据集,而是返回 3 个。

解决这个问题的最佳方法是构建一个虚拟表,用我的结果填充它,然后从中选择它们吗?

这是我到目前为止所拥有的:

DECLARE @startDate date, @endDate date;
DECLARE @counter int = 0;


WHILE @counter < 3 BEGIN
    --set start and end dates
    SELECT @startDate = CONVERT(date, (CONVERT(nvarchar, YEAR(DATEADD(YEAR,-1 * @counter, CONVERT(date, GETDATE())))) + '-02-01'));
    SELECT @endDate = DATEADD(YEAR,-1 * @counter, CONVERT (date, GETDATE()));

    --select results
    SELECT YEAR(ib.DateDelivered) [Year], SUM(ib.TotalAmountLessFreight) [YTD Sale]
    FROM InvoiceBase ib
    WHERE ib.DateDelivered < @endDate
        AND ib.DateDelivered > @startDate
    GROUP BY YEAR(ib.DateDelivered);

    --increment
    SET @counter = @counter + 1;
END
4

1 回答 1

1

最好的方法是在单个查询中。尝试:

;with cte as
(select i.*, 
        dateadd(year, datediff(year,DateDelivered,getdate()), getdate()) [YearEnd]
 FROM InvoiceBase i)
select YEAR(DateDelivered) [Year],
       SUM(case when DateDelivered <= YearEnd 
                then TotalAmountLessFreight end) [YTD Sales],
       SUM(case when DateDelivered <= YearEnd and 
                     month(DateDelivered) >= floor((month(YearEnd)+2)/3)*3-2
                then TotalAmountLessFreight end) [QTD Sales],
       SUM(case when DateDelivered <= YearEnd and 
                     datediff(month, DateDelivered, YearEnd) = 0
                then TotalAmountLessFreight end) [MTD Sales]
FROM cte
GROUP BY YEAR(DateDelivered)
于 2013-04-25T18:17:11.943 回答