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

发布于 2025-01-03 14:33:59 字数 613 浏览 3 评论 0原文

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。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

从来不烧饼 2025-01-10 14:33:59

您可以使用 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 中,这称为“旋转”。

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".

娇女薄笑 2025-01-10 14:33:59

也许类似于:

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

但您仍然必须在此处指定客户 ID。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文