所以我在这里有这个基本查询,我希望第二列的结果与外部/相关查询相关联:
SELECT
r1.OrderNo,
COUNT(r1.PartNo) AS [Pcs Complete]
FROM OrderRouting r1
WHERE r1.Status = 'Current'
AND r1.WorkCntr = 'Shipping'
GROUP BY r1.OrderNo
输出:
所以我正在尝试将第二列放在我的外部查询的选择列表中,所以它看起来像这样:
SELECT
CAST(r.OrderNo AS INT) AS OrderNo,
(
SELECT
r1.OrderNo,
COUNT(r1.PartNo)
FROM OrderRouting r1
WHERE r1.Status = 'Current'
AND r1.WorkCntr = 'Shipping'
GROUP BY r1.OrderNo
) AS [Pcs Complete]
FROM OrderRouting r
JOIN OrderDet od ON r.JobNo = od.JobNo
JOIN Orders o ON od.OrderNo = o.Orderno
WHERE r.Status = 'Current'
AND r.WorkCntr IN ('Cutting', 'Framing', 'Assembly', 'Shipping')
GROUP BY CAST(r.OrderNo AS INT)
现在显然这不起作用,因为内部选择只允许1列,但是如果我删除了r1.OrderNo列,我得到1个聚合应用于我的外部查询中的每个值,这不是我想要的。我如何关联它们?我试过这个:
SELECT
CAST(r.OrderNo AS INT) AS OrderNo,
(
SELECT
COUNT(r1.PartNo)
FROM OrderRouting r1
WHERE r1.Status = 'Current'
AND r1.WorkCntr = 'Shipping'
) AS [Pcs Complete]
FROM OrderRouting r
JOIN OrderDet od ON r.JobNo = od.JobNo
JOIN Orders o ON od.OrderNo = o.Orderno
WHERE r.Status = 'Current'
AND r.WorkCntr IN ('Cutting', 'Framing', 'Assembly', 'Shipping')
GROUP BY CAST(r.OrderNo AS INT)
输出(错误!):
而且:
SELECT
CAST(r.OrderNo AS INT) AS OrderNo,
(
SELECT
COUNT(r1.PartNo)
FROM OrderRouting r1 JOIN OrderRouting r ON r1.OrderNo = r.OrderNo
WHERE r1.Status = 'Current'
AND r1.WorkCntr = 'Shipping'
) AS [Pcs Complete]
FROM OrderRouting r
JOIN OrderDet od ON r.JobNo = od.JobNo
JOIN Orders o ON od.OrderNo = o.Orderno
WHERE r.Status = 'Current'
AND r.WorkCntr IN ('Cutting', 'Framing', 'Assembly', 'Shipping')
GROUP BY CAST(r.OrderNo AS INT)
两者都没有奏效,他们都返回了1个全局应用的聚合,与外部查询中的OrderNo列无关。也许我需要尝试其他的东西,我只需要一些指导,了解什么是实现我需要的最佳方式。 Thx提前
答案 0 :(得分:1)
我认为您可以使用左连接来显示所有现有订单号。
SELECT CAST(r.OrderNo AS INT) AS OrderNo,
r2.[Pcs Complete]
FROM OrderRouting r
JOIN OrderDet od ON r.JobNo = od.JobNo
JOIN Orders o ON od.OrderNo = o.Orderno
LEFT JOIN
(
SELECT CAST(r1.OrderNo AS INT) OrderNo,
COUNT(r1.PartNo) AS [Pcs Complete]
FROM OrderRouting r1
WHERE r1.Status = 'Current'
AND r1.WorkCntr = 'Shipping'
GROUP BY r1.OrderNo
) AS [r2] ON r2.OrderNo = r.OrderNo
WHERE r.Status = 'Current'
AND r.WorkCntr IN ('Cutting', 'Framing', 'Assembly', 'Shipping')
GROUP BY CAST(r.OrderNo AS INT)
答案 1 :(得分:0)
我并不完全清楚你要做什么,但我认为下面的代码会让你走上正确的道路:
SELECT
CAST(r.OrderNo AS INT) AS OrderNo
FROM OrderRouting r
JOIN OrderDet od ON r.JobNo = od.JobNo
JOIN Orders o ON od.OrderNo = o.Orderno
JOIN
(
SELECT r1.OrderNo,
COUNT(r1.PartNo)
FROM OrderRouting r1 JOIN OrderRouting r ON r1.OrderNo = r.OrderNo
WHERE r1.Status = 'Current'
AND r1.WorkCntr = 'Shipping'
) AS [PCsComplete] ON PcsComplete.OrderNo = r.OrderNo
WHERE r.Status = 'Current'
AND r.WorkCntr IN ('Cutting', 'Framing', 'Assembly', 'Shipping')
GROUP BY CAST(r.OrderNo AS INT)