如何在内部使用union?(SQL)

时间:2010-12-15 23:48:06

标签: sql sql-server-2005

我有以下代码,我想使用union命令来组合它们。我尝试使用带有和不带最后一个表(12)的union命令。请提前告诉你。

DECLARE @COUNTER as int
SET @COUNTER = 0
WHILE @COUNTER < 12
  BEGIN
   SET @COUNTER = @COUNTER + 1
SELECT e.Month,e.Code,e.AVERAGE,f.AVERAGE
FROM ( SELECT     @COUNTER as Month,Clients.Clients_Code as Code, AVG(Transactions.Amount_of_indebtedness) as AVERAGE
  FROM         Account INNER JOIN
                      Clients ON Account.Account_Number = Clients.Account_Number INNER JOIN
                      Credit_Card ON Account.Account_Number = Credit_Card.Account_Number INNER JOIN
                      Transactions ON Credit_Card.Credit_Number = Transactions.Credit_Number
WHERE     (YEAR(Transactions.Date_and_time_of_transaction) = '2009') AND (MONTH(Transactions.Date_and_time_of_transaction) < @COUNTER)
GROUP BY Clients.Clients_Code)e,
  ( SELECT     @COUNTER as Month,Clients.Clients_Code as Code, AVG(Transactions.Amount_of_indebtedness) as AVERAGE
  FROM         Account INNER JOIN
                      Clients ON Account.Account_Number = Clients.Account_Number INNER JOIN
                      Credit_Card ON Account.Account_Number = Credit_Card.Account_Number INNER JOIN
                      Transactions ON Credit_Card.Credit_Number = Transactions.Credit_Number
WHERE     (YEAR(Transactions.Date_and_time_of_transaction) = '2009') AND (MONTH(Transactions.Date_and_time_of_transaction) >= @COUNTER)
GROUP BY Clients.Clients_Code)f
WHERE f.Code=e.Code AND e.Month=f.Month AND f.AVERAGE>e.AVERAGE

END

1 个答案:

答案 0 :(得分:2)

你不能。

你能做的是:

  • 将结果插入#temp表或表变量,然后从最后选择
  • 使用cte或temp表来生成所需的数字,然后执行单个查询,而不是使用while循环。