3

SQL Server 初学者在这里。我在 SELECT/UPDATE 语句上遇到了一些问题。我有一个带有订单号列和行号列的表。下面的 select 语句返回我想要的值。我想获取结果并将该数字插入到订单号匹配的同一表上的列中。我是不是想太多了?或者也许在考虑复杂性?:)

    SELECT
    ORDNUM, COUNT(LINNUM) AS 'CountLines'
    FROM [TableName]
    WHERE STS = '3' AND DUEQTY < ONHAND AND STYPE = 'CU'
    GROUP BY ORDNUM

    UPDATE [TableName]
    SET LNCNT = 'CountLines'
    WHERE ORDNUM = ORDNUM

先感谢您。本

更新:我在下面使用了 Andomars 解决方案,效果很好。谢谢大家的帮助。

4

4 回答 4

12

使用 SQL Server 语法:

update  tn
set     LNCNT = SubQuery.CountLines
from    TableName as tn
join    (
        select  ordnum
        ,       count(linnum) as CountLines
        from    TableName
        where   sts = '3'
                and DUEQTY < ONHAND 
                and STYPE = 'CU'
        group by
                ordnum
        ) as SubQuery
on      SubQuery.ordnum = tn.ordnum
于 2012-08-16T15:27:56.903 回答
2

以下应该适用于 SQL Server:

with counts as
(
    SELECT
    ORDNUM, COUNT(LINNUM) AS 'CountLines'
    FROM [TableName]
    WHERE STS = '3' AND DUEQTY < ONHAND AND STYPE = 'CU'
    GROUP BY ORDNUM
)

    UPDATE tn
    SET tn.LNCNT = c.CountLines
    FROM TableName tn
    INNER JOIN counts as c
    ON tn.OrderNum = c.OrderNum
于 2012-08-16T15:27:46.670 回答
0

如果您在 MS SQL 中尝试过 DECLARE。

DECLARE @countlines INT 
SET @countlines = SELECT COUNT(LINNUM) FROM [AdvPickTicket] WHERE STS = '3' 
AND DUEQTY < ONHAND AND STYPE = 'CU' GROUP BY ORDNUM
UPDATE [TableName]
SET LNCNT = @countlines
WHERE ORDNUM = ORDNUM
于 2012-08-16T15:34:08.607 回答
0

试试这个

UPDATE [tablename]
SET LNCNT = abb.CountLines
FROM (SELECT 
    ORDNUM, COUNT(LINNUM) AS 'CountLines' 
    FROM [TableName] 
    WHERE STS = '3' AND DUEQTY < ONHAND AND STYPE = 'CU' 
    GROUP BY ORDNUM) AS abb 
于 2012-08-16T16:18:53.003 回答