选择With Multiple Where Criteria

时间:2013-04-25 17:38:14

标签: sql sql-server-2008 tsql

我正在尝试选择一系列不同的标准。我基本上将采取今天的日期,并将其用于我们的发票表,以确定我们今年如何形成,与过去几年相比。

最后,我基本上想要列出年份,年初销售,季度销售和月初销售的列。我已经开始为此创建一个循环,但我遇到的问题是它正在执行几个select,而不是返回一个数据集,而是返回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

1 个答案:

答案 0 :(得分: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)