我能够在特定日期之前三年和之后三年对项目进行分组,但我无法在三年内打破项目计数。你能好好看一下吗?
SELECT
ITEM,
CASE WHEN DATE >='12/6/02' AND DATE <'12/6/05' AND ITEM ='RICE' THEN 'RICE PRIOR'
CASE WHEN DATE >='12/06/05' AND DATE <'12/6/08' AND ITEM ='RICE' THEN 'RICE POST'
END AS TYPE,
COUNT (QTY) AS RICE
FROM #TEMP
WHERE DATE >='12/6/02'
AND DATE <'12/6/08'
GROUP BY ITEM,
CASE WHEN DATE >='12/6/02' AND DATE <'12/6/05' AND ITEM ='RICE' THEN 'RICE PRIOR'
CASE WHEN DATE >='12/06/05' AND DATE <'12/6/08' AND ITEM ='RICE' THEN 'RICE POST'
END
有人可以看一下,把它分解成三年吗?
运行此脚本,我的结果显示
Type, Rice
Rice Prior 444
Rice Post 555
我的愿望输出将是:
Year3, Year2, Year1 Year1, Year2, Year3
4 44 400 5 500 50
谢谢, 乔
答案 0 :(得分:2)
这应该使用pivot和date参数匹配您想要的查询,因此您不必在所有日期和条件下对其进行硬编码。
DATEADD
上述方法并未考虑闰年。您可以应用@ JPW的方法来使用知道闰年的DECLARE @D DATE = '12/6/2005'
SELECT
ITEM,
[-3] AS Year3,
[-2] AS Year2,
[-1] AS Year1,
[1] AS Year1,
[2] AS Year2,
[3] AS Year3
FROM (
SELECT
ITEM,
CASE
WHEN DATE BETWEEN DATEADD(YEAR, -3, @D) AND DATEADD(YEAR, -2, @D) THEN -3
WHEN DATE BETWEEN DATEADD(YEAR, -2, @D) AND DATEADD(YEAR, -1, @D) THEN -2
WHEN DATE BETWEEN DATEADD(YEAR, -1, @D) AND DATEADD(YEAR, -0, @D) THEN -1
WHEN DATE BETWEEN DATEADD(YEAR, +0, @D) AND DATEADD(YEAR, +1, @D) THEN 1
WHEN DATE BETWEEN DATEADD(YEAR, +1, @D) AND DATEADD(YEAR, +2, @D) THEN 2
WHEN DATE BETWEEN DATEADD(YEAR, +2, @D) AND DATEADD(YEAR, +3, @D) THEN 3
ELSE NULL END AS [YR],
QTY
FROM #TEMP
) T
PIVOT (MAX(QTY) FOR [YR] IN ([-3], [-2], [-1], [1], [2], [3])) PVT
。您只需要了解每个地区的第一天和最后一天的边界情景。在这种方法中,第一场比赛获胜,所以今天的日期将是年份&#34; -1&#34;。
{{1}}
答案 1 :(得分:1)
根据您的示例输出,我认为下面的查询可能就是您想要的。您可能需要调整日期范围以满足您的需求,但一般的想法应该是明确的:
DECLARE @d date = '2005-07-27';
WITH cte AS
(
SELECT
ITEM
, SUM(CASE WHEN DATE BETWEEN DATEADD(YEAR, -3, @D) AND DATEADD(YEAR, -2, @D) AND ITEM ='RICE' THEN QTY END) 'RICE PRIOR -3'
, SUM(CASE WHEN DATE BETWEEN DATEADD(YEAR, -2, @D) AND DATEADD(YEAR, -1, @D) AND ITEM ='RICE' THEN QTY END) 'RICE PRIOR -2'
, SUM(CASE WHEN DATE BETWEEN DATEADD(YEAR, -1, @D) AND DATEADD(YEAR, -0, @D) AND ITEM ='RICE' THEN QTY END) 'RICE PRIOR -1'
, SUM(CASE WHEN DATE BETWEEN DATEADD(YEAR, +0, @D) AND DATEADD(YEAR, +1, @D) AND ITEM ='RICE' THEN QTY END) 'RICE POST +1'
, SUM(CASE WHEN DATE BETWEEN DATEADD(YEAR, +1, @D) AND DATEADD(YEAR, +2, @D) AND ITEM ='RICE' THEN QTY END) 'RICE POST +2'
, SUM(CASE WHEN DATE BETWEEN DATEADD(YEAR, +2, @D) AND DATEADD(YEAR, +3, @D) AND ITEM ='RICE' THEN QTY END) 'RICE POST +3'
FROM #TEMP
WHERE DATE >='2002-05-12' AND DATE <'2008-06-12'
GROUP BY ITEM
)
SELECT * FROM CTE;
答案 2 :(得分:0)
所以基本上你可以在PIVOT的选择部分中应用你的计数逻辑,然后在几年内转动结果集
SELECT ITEM, [2002] AS[Year-3],[2003] AS [Year-2], [2004] AS [Year-1],
[2005] AS [Year1],[2006] AS [Year2],[2007] AS [Year3]
FROM (
-- Your logic here
SELECT
ITEM,
YEAR(Date) as Y,
COUNT (quantity) AS RICE
FROM [dbo].[temp]
WHERE DATE >='12/6/01'
AND DATE <'12/6/08'
GROUP BY ITEM,YEAR(Date)
) as s
PIVOT
(
SUM(RICE)
FOR Y IN ([2002], [2003], [2004], [2005],[2006],[2007])
)AS p
Sql小提琴链接 http://sqlfiddle.com/#!6/fa406/2