我想在不使用SQL Server中的多个更新语句的情况下使用另一个表更新一个包含多组结果的表

时间:2016-06-09 20:47:01

标签: sql-server

如何在不使用SQL Server中的多个更新语句的情况下使用单个语句填充tb_1?然后,如果BU有多个细分市场,消费者,批发等等,该怎么办?他们都有相同的产品。

假设您有超过10种产品。

UPDATE tb_1
SET CurrYear = (SELECT SUM(CNT)
                FROM tb_2
                WHERE PRODUCT_GROUP IN ('Product1')
                AND SEGMENT Like 'Consumer%' ----(Consumer PP, Consumer Post)
WHERE Metric = 'Product1'
AND BU = 'Consumer'

--- here we add Product2

UPDATE tb_1
SET CurrYear = (SELECT SUM(CNT)
                FROM tb_2
                WHERE PRODUCT_GROUP IN ('Product2')
                AND SEGMENT IN ('Business', 'Retail'))
WHERE Metric = 'Product2'
AND BU = 'Enterprise'

----Here We Add Another Product for different Segments

UPDATE tb_1
SET CurrYear = (SELECT SUM(CNT)
                FROM tb_2
                WHERE PRODUCT_GROUP IN ('Product1')
                AND SEGMENT IN ('OLO', 'WS'))   ---Wholesale = (OLO + WS)
WHERE Metric = 'Product1
AND BU = 'Wholesale'

2 个答案:

答案 0 :(得分:1)

使用这样的查询:

UPDATE tb_1
SET CurrYear = (
                SELECT SUM(CNT)
                FROM tb_2
                WHERE PRODUCT_GROUP = tb_1.Metric
                AND SEGMENT IN ('Business', 'Retail')
                )
WHERE BU = 'Enterprise'
    -- if you need to filter -- uncomment
    --AND Metric IN ('Product 1', 'Product 2')

您可以使用 UPDATE 语句中的表名或别名。

答案 1 :(得分:0)

使用通用表格表示简洁和提高可读性。

WITH cte AS
(
    SELECT PRODUCT_GROUP, SUM(CNT) AS CNT
    FROM tb_2
    WHERE SEGMENT IN ('Business', 'Retail')
)
UPDATE tb_1 SET CurYear = cte.CNT
    FROM tb_1 INNER JOIN cte ON tb_1.Metric = cte.PRODUCT_GROUP