我在“订单”表中添加了“FirstDesignTitle”列,并尝试更新其初始值(然后通过业务逻辑使其保持最新)。我的表是:
Orders
------
OrderID
FirstDesignTitle
LineItem
--------
LineItemID
OrderID
DesignID
Design
------
DesignID
DesignTitle
“First”表示具有DesignID的最低LineItemID'd LineItem(该列可以为空)。我得到的更新声明是:
UPDATE Orders
SET FirstDesignTitle = t.DesignTitle
FROM (
SELECT TOP (1) [t4].[value] as DesignTitle
FROM (
SELECT (
SELECT [t3].[DesignTitle]
FROM (
SELECT TOP (1) [t1].[DesignID]
FROM [dbo].[LineItem] AS [t1]
WHERE ([t1].[DesignID] IS NOT NULL) AND ([t1].[OrderID] = [t0].[OrderID])
ORDER BY [t1].[LineItemID] ASC
) AS [t2]
LEFT OUTER JOIN [dbo].[Design] AS [t3] ON [t3].[DesignID] = [t2].[DesignID]
) AS [value], [t0].[OrderID]
FROM [dbo].[Orders] AS [t0]
) AS [t4]
WHERE [t4].[OrderID] = orderid
ORDER BY DesignTitle DESC
) t
但是,我只得到一个DesignTitle来填充所有订单,而不是我想要的,这是每个订单显示其第一个LineItem的DesignTitle。填充的DesignTitle是Designs表中最后一个DesignTitle,以字母“ZZZ”开头。谁能描述/修复我做错了什么?
答案 0 :(得分:2)
这是使用CTE实现目标的方法
;WITH CTELineItem
AS
(
SELECT Sequence = ROW_NUMBER() OVER(PARTITION BY OrderID ORDER BY LineItemID ASC),
OrderID,
DesignID
FROM LineItem
WHERE DesignID IS NOT NULL
)
UPDATE Orders
SET Orders.FirstDesignTitle = Design.DesignTitle
FROM Orders
INNER JOIN CTELineItem AS FirstLineItem ON FirstLineItem.Sequence = 1
AND Orders.OrderID = FirstLineItem.OrderID
INNER JOIN Design ON FirstLineItem.DesignID = Design.DesignID
答案 1 :(得分:1)
我不知道为什么你的查询不起作用。另一种方法使用相关子查询:
update orders
set firstdesigntitle = (select top 1 d.designtitle
from lineitem li join
design d
on li.designid = d.designid
where li.orderid = orders.orderid
order by d.designid asc
);
您没有指定如何定义“first”。这使用最小的designid
。