0

尝试使用别名的子查询

SELECT
  *, 
  IQ.EndPart, 
  IQ.QtyToShip 
FROM
  parts p
  INNER JOIN (
     select
       *, 
       (case when c.kitno is null then l.partno else c.partno end) as [EndPart],
       (case when c.kitno is null then l.TotalQuantity else c.reqqty end) as [QtyToShip]
     FROM 
       shipments s
       INNER JOIN shipments_li l ON s.ShipmentNo = l.ShipmentNo 
       LEFT JOIN ProductConfiguration c ON l.PartNo = c.KitNo WHERE s.Status='N' and year(s.OrderDate)>2007
   ) IQ ON p.partno = IQ.EndPart

使用别名为 EndPart 的零件 # 寻找一种将零件表连接到我下面的查询的方法。如果有另一种方法来实现取两列并将它们组合而不是大小写和别名的结果,那也是一个很好的选择。我对其他人的所有搜索都寻求实现相同的结果,结果您无法基于别名执行连接,因为当时尚未确定结果,建议使用子查询作为解决方法。我只是不确定如何获得工作成果。上面的查询是我试图开始工作的。任何帮助表示赞赏。提前致谢。

原始查询

SELECT
  *, 
  (case when c.kitno is null then l.partno else c.partno end) as [EndPart],
  (case when c.kitno is null then l.TotalQuantity else c.reqqty end) as [QtyToShip]
FROM
  shipments s
  INNER JOIN shipments_li l ON s.ShipmentNo = l.ShipmentNo
  LEFT JOIN ProductConfiguration c ON l.PartNo = c.KitNo
WHERE
  s.Status='N'
  and year(s.OrderDate)>2007
order by s.shipmentno
4

1 回答 1

0

更合适的方式

--- CREATE TempTable
DECLARE @tblTemp AS TABLE (EndPart INT,
                       QtyToShip INT)

INSERT INTO @tblTemp (EndPart, QtyToShip)
SELECT 
       (CASE WHEN c.kitno IS NULL 
             THEN l.partno ELSE c.partno END) AS [EndPart],
       (CASE WHEN c.kitno IS NULL 
            THEN l.TotalQuantity 
            ELSE c.reqqty END) AS [QtyToShip]
FROM dbo.Shipments s WITH(NOLOCK)
INNER JOIN shipments_li l WITH(NOLOCK) ON s.ShipmentNo = l.ShipmentNo 
LEFT JOIN ProductConfiguration c WITH(NOLOCK) ON l.PartNo = c.KitNo 
WHERE s.Status='N' AND YEAR(s.OrderDate)>2007

SELECT
   p.*, 
  tmp.EndPart, 
  tmp.QtyToShip 
FROM dbo.parts p WITH(NOLOCK)
  INNER JOIN @tblTemp tmp ON  p.partno = tmp.EndPart
于 2013-01-14T17:35:33.423 回答