使用约束中的变量多次运行脚本

时间:2012-02-07 21:40:32

标签: sql variables loops where

table

是否有一种方法可以填充Table2中的Cust1,Cust2,Cust3列,这些列不涉及使用多个不同的“WHERE”子句运行相同的查询?

例如,现在我会采取这样做:

INSERT INTO Table2(Cust1_Totals)
SELECT Fruit, SUM(quantity)
FROM Table1
WHERE Customer_ID LIKE 1
GROUP BY Fruit

INSERT INTO Table2(Cust2_Totals)
SELECT Fruit, SUM(quantity)
FROM Table1
WHERE Customer_ID LIKE 2
GROUP BY Fruit

INSERT INTO Table2(Cust3_Totals)
SELECT Fruit, SUM(quantity)
FROM Table1
WHERE Customer_ID LIKE 3
GROUP BY Fruit

理想情况下,我希望有一个具有所有唯一客户的Customer_ID列的另一个表,然后我将在上述查询的循环中引用每个表。 SQL Server 2008。

2 个答案:

答案 0 :(得分:4)

您可以使用case在不同的列中为每位客户生成总和:

INSERT  Table2
        (Produce, Cust1_Totals, Cust2_Totals, Cust3_Totals)
SELECT  Fruit
,       SUM(case when Customer_ID = 1 then quantity end)
,       SUM(case when Customer_ID = 2 then quantity end)
,       SUM(case when Customer_ID = 3 then quantity end)
FROM    Table1
WHERE   Customer_ID IN (1,2,3)
GROUP BY 
        Fruit

生成可变数量的列需要动态sql。让Excel通常更容易。在Excel中,它被称为“旋转”。

答案 1 :(得分:0)

可能是这样的:

select * from table1
pivot (sum(quantity) for customerid in ([1], [2], [3])) as pivotTable

但您仍需在此处指定客户ID。