需要将带有HAVING的SELECT语句转换为UPDATE Set命令

时间:2014-01-14 18:06:33

标签: sql having

如何更改以下SELECT声明,以便更新SALESSTATUS = 4JSDETAILEDSTATUS = 4

SELECT     
  JSCONTINUITYCUSTHEADER.SALESID AS PARENT, 
  SALESLINE.SALESSTATUS, 
  SALESLINE.JSDETAILEDSTATUS
FROM JSCONTINUITYCUSTLINE 
INNER JOIN JSCONTINUITYCUSTHEADER ON JSCONTINUITYCUSTLINE.DATAAREAID = JSCONTINUITYCUSTHEADER.DATAAREAID 
AND JSCONTINUITYCUSTLINE.INVENTTRANSID = JSCONTINUITYCUSTHEADER.INVENTTRANSID 
INNER JOIN SALESLINE ON JSCONTINUITYCUSTHEADER.SALESID = SALESLINE.SALESID 
AND JSCONTINUITYCUSTHEADER.DATAAREAID = SALESLINE.DATAAREAID 
AND JSCONTINUITYCUSTHEADER.INVENTTRANSID = SALESLINE.INVENTTRANSID
WHERE     
  (JSCONTINUITYCUSTLINE.DATAAREAID = N'CSN') 
  AND (JSCONTINUITYCUSTLINE.SALESID <> N' ') 
  AND (JSCONTINUITYCUSTLINE.SALESQTY <> 0) 
  AND (SALESLINE.SALESSTATUS = 1)
GROUP BY 
  JSCONTINUITYCUSTHEADER.SALESID, 
  SALESLINE.SALESSTATUS, 
  SALESLINE.JSDETAILEDSTATUS
HAVING
  (MAX(JSCONTINUITYCUSTLINE.STARTDATE) < CONVERT(DATETIME, '2012-07-01 00:00:00', 102))
  AND (JSCONTINUITYCUSTHEADER.SALESID <> N' ')
ORDER BY PARENT

1 个答案:

答案 0 :(得分:0)

将表名作为别名是一个好习惯。 使用NULL代替''并替换条件CL.SALESID IS NOT NULL 我不明白CH.SALESID&lt;&gt; N''在HAVING条款......

BEGIN TRAN
    UPDATE SALESLINE
    SET
        SL.SALESSTATUS = 4, 
        SL.JSDETAILEDSTATUS = 4
    FROM
        SALESLINE SL  
        INNER JOIN JSCONTINUITYCUSTHEADER CH
            ON CL.DATAAREAID = CH.DATAAREAID AND CL.INVENTTRANSID = CH.INVENTTRANSID 
        INNER JOIN JSCONTINUITYCUSTLINE CL
            ON CH.SALESID = SL.SALESID AND CH.DATAAREAID = SL.DATAAREAID AND CH.INVENTTRANSID = SL.INVENTTRANSID
    WHERE     
        CL.DATAAREAID = N'CSN'
        AND CL.SALESID <> N' ' 
        AND CL.SALESQTY <> 0) 
        AND SL.SALESSTATUS = 1
    GROUP BY 
        CH.SALESID,
        SL.SALESSTATUS, 
        SL.JSDETAILEDSTATUS
    HAVING
        MAX(CL.STARTDATE) < CONVERT(DATETIME, '2012-07-01 00:00:00', 102)



-- Check you UPDATE is correctly performed
ROLLBACK TRAN