使用约束中的变量多次运行脚本
有没有一种方法可以填充 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。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
case
在单独的列中生成每个客户的总和:生成可变数量的列将需要动态 SQL。通常让 Excel 更容易做到这一点。在 Excel 中,这称为“旋转”。
You could use
case
to generate sums per customer in separate columns: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".
也许类似于:
但您仍然必须在此处指定客户 ID。
Maybe something like:
But you still have to specify the customer IDs here.