SQL多选查询并在同一个表上相交

时间:2016-04-20 10:56:02

标签: sql-server

我正在查询根据表格的第三列(S)的前200位得到三列(A,B,S)(这有一些条件检查)。

SELECT TOP 200 PlantId, SKU, SUM(Demand)
FROM NetDemandTable
WHERE DemandWKId>=62 AND DemandWKId<=76
GROUP BY PlantId, SKU
ORDER BY SUM(Demand) DESC

结果列B被视为另一个选择查询的唯一记录,该查询又是A,B,S列,但条件不同,此列B应与选择查询1中获得的结果相交。

SELECT PlantId, SKU, SUM(Demand)
FROM CuringNetDemandCopy
WHERE DemandWKId < 62 
GROUP BY PlantId, SKU  
ORDER BY SUM(Demand) DESC

现在第二个查询结果应该只选择从第一个查询中获得的B列中的SKU实体。

1 个答案:

答案 0 :(得分:0)

试试这个:

with  cte as 
(
SELECT TOP 200 PlantId, SKU, SUM(Demand)
FROM NetDemandTable
WHERE DemandWKId>=62 AND DemandWKId<=76
GROUP BY PlantId, SKU
)

SELECT PlantId, SKU, SUM(Demand)
FROM CuringNetDemandCopy
WHERE DemandWKId < 62  and SKU in (select distinct SKU from cte)
GROUP BY PlantId, SKU  
ORDER BY SUM(Demand) DESC