1

table

Is there a way of populating the Cust1, Cust2, Cust3 columns in Table2 that doesn't involve running the same query with several different "WHERE" clauses?

For example, right now I would resort to doing this:

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

Ideally, I would like to have another table with a Customer_ID column of all the unique customers and then I would reference each one in a loop in the above query. SQL Server 2008.

2 Answers 2

4

You could use case to generate sums per customer in separate columns:

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

Generating a variable numbers of columns would require dynamic sql. It's usually easier to let Excel that. In Excel-speak, it's known as "pivoting".

Sign up to request clarification or add additional context in comments.

1 Comment

This seems like a good idea, but I am worried about instances where I will have about 10 sets of columns per "customer" to populate. This would lead to a lot of lengthy statements. Would things be different if I had a fixed # of customers in another table? I don't really need this to be dynamic. I just want it to run for each customer in the other table.
0

Maybe something like:

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

But you still have to specify the customer IDs here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.