使用另一个表中的运算符更新基于参数的数据

时间:2014-06-13 06:05:32

标签: sql sql-server sql-server-2008

我有2张表格,其中包含以下示例数据:

tblSale     
PartCode    PartGroup   SaleQty
a   FM  600
b   MM  202
c   SM  10
d   NM  0

tblCondition        
PartGroup   Condition   
FM  >500    
MM  >=200   
SM  >=1 
NM  0   

在SQL Server存储过程中,我想根据PartGrouptblSalePartGroup更新tblCondition中的sum(SaleQty)并与Condition进行比较

请帮助。

更新:

enter image description here

实施例: PartCode'A'具有PartGroup ='FM'和SaleQty = 500。 如果SaleQty = 400,则根据tblCondition中的条件更新PartGroup ='MM'。

UPDATE tblSale
SET tblSale.PartGroup=tblCondition.PartGroup
WHERE SUM(tblSale.Sale) ??? tblCondition.Condition

2 个答案:

答案 0 :(得分:1)

使用此

update ts set partGroup = something
from tblSale ts
inner join tblCondition tc 
        on tc.PartGroup=ts.PartGroup
inner join (Select PartGroup, sum(SaleQty) as SumSaleQty
            from tblSale
            group by PartGroup) as sums 
        on sums.PartGroup = tc.PartGroup 
           and sums.SumSaleQty >= tc.Condition

答案 1 :(得分:1)

如果没有动态代码,我认为你无法做到这一点。

对于我的解决方案,您需要进行一些更改/注释:

  • 将PartGroup NM条件0更改为=0
  • 确保将tblCondition表条件从最大(500)插入到最低(0)

首先,我要为tblCondition表中的每一行创建CASE

然后我按PartCode将数据汇总到临时表(我将PartCode' c'分成两行进行测试)

最后,创建动态代码,它将更新数据

/*

CREATE TABLE #tblSale ( PartCode VARCHAR(10), PartGroup VARCHAR(10), SaleQty INT)

INSERT INTO #tblSale SELECT 'a', 'FM', 600
INSERT INTO #tblSale SELECT 'b', 'MM', 202
INSERT INTO #tblSale SELECT 'c', 'SM', 5
INSERT INTO #tblSale SELECT 'd', 'NM', 0
INSERT INTO #tblSale SELECT 'c', 'SM', 5


CREATE TABLE #tblCondition ( PartGroup VARCHAR(10), Condition VARCHAR(10))
INSERT INTO #tblCondition SELECT 'FM', '>500'    
INSERT INTO #tblCondition SELECT 'MM', '>=200'   
INSERT INTO #tblCondition SELECT 'SM', '>=1'
INSERT INTO #tblCondition SELECT 'NM', '=0'

*/

--CREATE CASES
DECLARE @CaseStr NVARCHAR(1000) = 'CASE '

SELECT @CaseStr = @CaseStr + '
        WHEN SaleSUM ' + Condition + ' THEN '''+ PartGroup + ''' '
FROM #tblCondition

SET @CaseStr = @CaseStr + ' END'


-- SUM data by PartCode
SELECT PartCode, SUM(SaleQty) AS SaleSUM
INTO #tblSaleSUM
FROM #tblSale
GROUP BY PartCode


-- Create dynamic code for update
DECLARE @query NVARCHAR(MAX)

SET @query = N'

UPDATE S
    SET S.PartGroup = SS.PartGroup
FROM #tblSale AS S
INNER JOIN 
    (
        SELECT PartCode, ' + @CaseStr + ' AS PartGroup
        FROM #tblSaleSUM
    ) AS SS
    ON SS.PartCode = S.PartCode

'

EXEC sp_executesql @query