SQL Server - 更新table1中具有最大条件的table1

时间:2015-03-24 14:34:53

标签: sql-server updates

我对SQL很新。这个网站是一个很好的资源,到目前为止我找到了很多问题的答案。现在我有点卡住了,所以现在是我第一个问题的时候了。

我在SQL Server 2012中工作。如何在FLAG = 'Y'时更新START_DATE = (SELECT CONTRACT, MIN(START_DATE) FROM #CONTR GROUP BY CONTRACT)

CREATE TABLE #CONTR
(
CONTRACT        INT ,       -- PRIMARY KEY COL1
CONTRACT_LINE   INT ,       -- PRIMARY KEY COL2
START_DATE      INT ,       -- 0 = CURRENT MONTH, -3 = THREE MONTHS IN PAST
FLAG            VARCHAR(1)  -- 'Y' OR 'N', DEFAULTED TO 'N' WHEN TABLE POPULATED
)

这似乎不应该那么困难,但我似乎无法让它发挥作用。

2 个答案:

答案 0 :(得分:0)

INSERT INTO #CONTR VALUES (1,1,100,'N')
INSERT INTO #CONTR VALUES (1,1,200,'N')

INSERT INTO #CONTR VALUES (2,1,100,'N')
INSERT INTO #CONTR VALUES (2,1,200,'N')

UPDATE
    c
SET
    c.FLAG = 'Y'
FROM
    #CONTR c
    JOIN (
           SELECT
            CONTRACT _CONTRACT ,
            MAX(START_DATE) _START_DATE
           FROM
            #CONTR
           GROUP BY
            CONTRACT
         ) mc ON c.CONTRACT = mc.[_CONTRACT] AND c.START_DATE = mc.[_START_DATE]

另一种方法。它完全相同,只是语法不同:

UPDATE
    c
SET
    c.FLAG = 'Y'
FROM
    #CONTR c
    CROSS APPLY (
           SELECT
            c1.CONTRACT _CONTRACT 
           FROM
            #CONTR c1
            WHERE c1.CONTRACT = c.CONTRACT
           GROUP BY
            CONTRACT
            HAVING MAX(c1.START_DATE) = c.START_DATE  
         ) mc;

结果:

SELECT * FROM #CONTR
CONTRACT    CONTRACT_LINE   START_DATE  FLAG
1   1   100 N
1   1   200 Y
2   1   100 N
2   1   200 Y

答案 1 :(得分:0)

UPDATE #CONTR
SET    FLAG = 'Y'
FROM #CONTR C1
     JOIN 
     (SELECT CONTRACT, MIN(START_DATE) AS START_DATE FROM #CONTR GROUP BY CONTRACT) C2
     ON C1.START_DATE = C2.START_DATE