我正在尝试将3个不同的表合并为一个查询中的一行,但是存在一些问题。目前我有四个桌子。 PaintSched,Painted_Log,Paint_Defect和Paint_Inspection。
PaintSched-单一条目,当计划程序仅计划要绘制的某些零件时
LOT QTY
1 150
2 100
Painted_Log-然后油漆部门拿了很多,并说出他们能够油漆多少
LOT(FK) QTYPainted
1 145
2 100
Paint_Defect-涂完零件后进行涂漆检查的缺陷主清单。我们手工检查我们喷涂的所有零件的质量。
DID Defect
1 Scratch
2 Paint Run
Paint_Inspection-每次发现缺陷时,检查员都会点击一个相关按钮,并记录以下内容。 Lot是FK,DID代表Paint_Defect中的缺陷ID。数量始终为1
Lot(FK) DID(FK) QTY
1 1 1
1 1 1
1 2 1
1 1 1
2 2 1
1 2 1
2 1 1
我想要得到的是以下输出:
Lot Sched Painted Scratch Paint Run
1 150 145 3 2
2 100 100 1 1
我已经尝试了以下方法:
SELECT PaintSched.Scheduled, PaintSched.Lot, PaintSched.qty, PaintSched.Is_Painted, Painted_Log.falloff
FROM PaintSched
INNER JOIN Painted_Log ON PaintSched.Lot = Painted_Log.lot
INNER JOIN MPA_Desc ON MPA_Desc.MPAID = PaintSched.MPAID
inner JOIN (
SELECT lot, sum(Paint_Inspection.qty) as seds
FROM Paint_Inspection
WHERE Paint_Inspection.Status = '1'
) AS seeds ON PaintSched.Lot = Paint_Inspection.Lot
答案 0 :(得分:1)
两件事:
在下面查看对查询的修改:
SELECT
PaintSched.Scheduled,
PaintSched.Lot,
PaintSched.qty,
PaintSched.Is_Painted,
Painted_Log.falloff
FROM PaintSched
INNER JOIN Painted_Log ON PaintSched.Lot = Painted_Log.lot
INNER JOIN MPA_Desc ON MPA_Desc.MPAID = PaintSched.MPAID
INNER JOIN (
SELECT lot, sum(Paint_Inspection.qty) as seds
FROM Paint_Inspection
WHERE Paint_Inspection.Status = '1'
GROUP BY Paint_Inspection.lot -- Missing GROUP BY
) AS seeds
ON PaintSched.Lot = seeds.Lot
答案 1 :(得分:1)
SELECT
PS.Lot,
PS.Qty Sched,
Painted,
Scratch,
PaintRun
FROM PaintSched PS
LEFT JOIN (SELECT
Lot,
SUM(QTYPainted) Painted
FROM Painted_Log GROUP BY Lot) PL
ON PS.Lot = PL.Lot
LEFT JOIN (SELECT
Lot,
SUM(CASE WHEN DID = 1 THEN 1 ELSE 0 END) Scratch,
SUM(CASE WHEN DID = 2 THEN 1 ELSE 0 END) PaintRun
FROM Paint_Inspection GROUP BY Lot) PI
ON PS.Lot = PI.Lot
上面的代码使用条件和将缺陷计数按类型汇总,然后再将其加入到批号中。如果您有2种以上的状态,则需要相应地更新上述代码。