SQL选择查询到另一个查询

时间:2017-03-21 20:41:07

标签: sql select

我是SQL的初学者,如果我的术语/编码稍微偏离,或者可能有点偏离,请提前道歉。 我有两个问题,我想加入一个。第一个创建包含两个特定进程的productid列表。 然后我想在第二个查询中使用这些productids。

以下也是正确的? group by products.productid having(sum(processid如'pick%'然后1 else 0 end)+ sum(caseid如'pack%'然后1 else 0 end)= 2)

任何帮助都会非常感激,希望这是有道理的。

SELECT
Products.ProductID
FROM Products
INNER JOIN Categories ON Products.Category = Categories.Category
INNER JOIN Boms ON Products.Product = Boms.Product AND Boms.BomVersion = Products.BomVersion
LEFT OUTER JOIN Products AS Comp ON Boms.Component = Comp.Product 
LEFT OUTER JOIN Processes  ON Boms.Process = Processes.Process
WHERE   
products.active = 1
and Categorys.Categoryid in ('5','20')
group by products.productid
having (sum(case when processid like 'pick%' then 1 else 0 end) + sum(case when processid like 'pack%' then 1 else 0 end) = 2)
order by products.productid


SELECT
Products.ProductID,
Products.productdescription,
Boms.Type As Type,
Comp.ProductId as Component,
Comp.productdescription,
Boms.Quantity,
BomVersions.BomVersionID,
Processes.processid,
Processes.ProcessDescription
FROM Products
INNER JOIN Categories ON Products.Category = Categories.Category
INNER JOIN Boms ON Products.Product = Boms.Product AND Boms.BomVersion = Products.BomVersion
LEFT OUTER JOIN Products AS Comp ON Boms.Component = Comp.Product 
LEFT OUTER JOIN Processes  ON Boms.Process = Processes.Process
INNER JOIN BomVersions ON Products.BomVersion = BomVersions.BomVersion
WHERE   
products.active = 1

order by products.productid, products.type,comp.productid

1 个答案:

答案 0 :(得分:0)

要合并它们,您可以执行以下操作。

SELECT b.*
FROM 
  (SELECT Products.ProductID FROM Products INNER JOIN ...) AS a
   INNER JOIN
  (SELECT Products.ProductID, Products.productdescription, Boms.Type As Type, ...) AS b
   ON a.ProductID = b.ProductID