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解决方案,效果很好。谢谢大家的帮助。
答案 0 :(得分:9)
使用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
答案 1 :(得分:1)
以下内容适用于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
答案 2 :(得分: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
答案 3 :(得分: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