使用SQL Server CTE复制临时表查询的结果

时间:2015-07-23 20:43:11

标签: sql sql-server common-table-expression

我已经解决了我上班时遇到的问题 - 我刚用临时表解决了这个问题 - 如果可能的话,我宁愿用CTE来解决它。你的帮助表示赞赏。

问题是确定会议出席率。但是,扭曲的是,确定在过去的5年中有多少与会者参加了会议。

这是有效的,代码(有点长 - 对不起......):

DECLARE @cnt INT = 2006;
CREATE table #MeetingMatrix (MEETING varchar(10), Year Int);
CREATE table #Attendees     (Year Int, ID varchar(10));
CREATE table #RollUp        (Year Int, Matches Int);

-- Create table of meetings 
INSERT INTO #MeetingMatrix (MEETING, [Year])
SELECT MEETING, CAST(Year(END_DATE) AS Int) FROM MEET_MASTER 
WHERE MEETING_TYPE='CONV' 
  AND (Year(END_DATE) > 2000 AND YEAR(END_DATE) < 2016); 

-- Create table of EVERYONE who has gone over the years 
INSERT INTO #Attendees ([Year], ID)
SELECT DISTINCT MM.Year, Orders.ST_ID
FROM Orders
INNER JOIN Order_Lines on ( Orders.Order_Number = Order_Lines.Order_Number )
INNER JOIN Product ON ( Order_Lines.Product_Code = Product.Product_Code )
INNER JOIN #MeetingMatrix MM ON PRODUCT_MAJOR=MM.MEETING
GROUP BY MM.Year, Orders.ST_ID;

-- Create yearly results desired
WHILE @cnt <= YEAR(GetDate())
BEGIN
  INSERT INTO #RollUp ([Year], Matches)
  SELECT @cnt, Count(*) FROM (
    SELECT @cnt 'Year', [ID], Count(*) 'Cnt'
    FROM #Attendees
    WHERE [Year] > (@cnt-5) AND [Year] <= @cnt
    GROUP BY [ID]
    HAVING Count(*) > 2) AS R

  SET @cnt = @cnt + 1;
END;

-- display year results
SELECT * FROM #RollUp

-- clean up

现在我必须通过CTE开始做同样的事情 - 我只是不确定如何度过每一年,然后确定前5年的结果(并计算个别与会者是否有这5年中有3个或更多):

WITH MeetingMatrix AS (
  SELECT Year(END_DATE) 'Year', MEETING FROM MEET_MASTER 
  WHERE MEETING_TYPE='CONV' 
    AND (Year(END_DATE) > 2000 AND YEAR(END_DATE) < YEAR(GetDate())) 
  )

, AttendeesOverSpan AS (
  SELECT DISTINCT Product.PRODUCT_MAJOR, MM.Year, Orders.ST_ID
  FROM Orders
  INNER JOIN Order_Lines on ( Orders.Order_Number = Order_Lines.Order_Number )
  INNER JOIN Product ON ( Order_Lines.Product_Code = Product.Product_Code )
  INNER JOIN MeetingMatrix MM ON PRODUCT_MAJOR=MEETING
  WHERE Orders.Status Not Like 'C%' 
    AND Order_Lines.Quantity_Ordered > 0 
    AND Product.Category in ( 'RB', 'TK' )
    AND (Lower(Product.ATTRIBUTES) <> 'comp' )
  GROUP BY Product.PRODUCT_MAJOR, MM.Year, Orders.ST_ID)

--, RollUpAttendees AS (

--)

SELECT ST_ID, Count(*) 'Cnt'
FROM AttendeesOverSpan
WHERE [Year] > 2010 AND [Year] < 2016
GROUP BY ST_ID
HAVING Count(*) > 2
ORDER BY Cnt Desc

有谁能告诉我如何在这里继续CTE路径?

所有帮助表示赞赏。

斯科特 图森,亚利桑那州

1 个答案:

答案 0 :(得分:0)

这很容易:

  1. 在您的CTE链中包含一个查询以获取所有年份:,someyears as (select distinc [year] as cnt from ...)
  2. 尝试使用你的循环,加入此表。
  3. 样品:

    SELECT cnt, Count(*) FROM (
        SELECT cnt 'Year', [ID], Count(*) 'Cnt'
        FROM AttendeesOverS inner join someyears on
      [Year] > (@cnt-5) AND [Year] <= @cnt
        GROUP BY [ID]
        HAVING Count(*) > 2) ...