我有这个查询。它工作但不正确。
SELECT
mc.Quantity as Production,
mc.Data as Date,
mc.Machine as Equipment,
mc.DesignSpeed,
k.Value,
SUM(l.DurationInMinutes)/60 as DurationInMinutes
FROM
Machine_Counter mc INNER JOIN
Linkup_Time l ON (mc.Data = l.ProductionDate AND mc.Machine = l.Machine) INNER JOIN
KPI_Value k ON (mc.Data = k.Data AND mc.Machine = k.Machine)
WHERE
mc.CounterType = 1 AND
mc.Machine LIKE @MACHINE AND
k.KPI = 3 AND
mc.Data BETWEEN @DATA_START AND @DATA_END AND
l.ReasoneCode LIKE '%7%'
GROUP BY
mc.Quantity,
mc.Data,
mc.Machine,
mc.DesignSpeed,
k.Value
ORDER BY mc.Data
问题在于第一次INNER JOIN
Machine_Counter mc INNER JOIN
Linkup_Time l ON (mc.Data = l.ProductionDate AND mc.Machine = l.Machine)
因为如果在Linkup_Time表中没有任何带有' ReasoneCode'的记录。像7,我没有收到任何记录。
如果在表Linkup_Time中,那台机器当天的那段时间内没有一个值,那么我也想要结果。
我尝试使用LEFT JOIN但结果是一样的。
答案 0 :(得分:1)
使用l.ReasoneCode LIKE '%7%'
时,左连接被视为INNER JOIN,因为Machine_Counter
表为空。
在ON
子句中为on join而不是where子句添加此条件。
SELECT
mc.Quantity as Production,
mc.Data as Date,
mc.Machine as Equipment,
mc.DesignSpeed,
k.Value,
SUM(l.DurationInMinutes)/60 as DurationInMinutes
FROM Machine_Counter mc
LEFT JOIN Linkup_Time l ON (mc.Data = l.ProductionDate
AND mc.Machine = l.Machine
AND l.ReasoneCode LIKE '%7%')
INNER JOIN
KPI_Value k ON (mc.Data = k.Data AND mc.Machine = k.Machine
AND k.KPI = 3 )
WHERE mc.CounterType = 1
AND mc.Machine LIKE @MACHINE
AND mc.Data BETWEEN @DATA_START AND @DATA_END
GROUP BY
mc.Quantity,
mc.Data,
mc.Machine,
mc.DesignSpeed,
k.Value
ORDER BY mc.Data
答案 1 :(得分:0)
这是因为您甚至在WHERE
子句中过滤了Linkup_Time
表中的一列。
试试这个:
SELECT mc.Quantity as Production
,mc.Data as Date
,mc.Machine as Equipment
,mc.DesignSpeed
,k.Value
,SUM(l.DurationInMinutes)/60 as DurationInMinutes
FROM Machine_Counter mc
LEFT JOIN Linkup_Time l
ON (mc.Data = l.ProductionDate AND mc.Machine = l.Machine)
INNER JOIN KPI_Value k
ON (mc.Data = k.Data AND mc.Machine = k.Machine)
WHERE mc.CounterType = 1
AND mc.Machine LIKE @MACHINE
AND k.KPI = 3
AND mc.Data BETWEEN @DATA_START AND @DATA_END
AND (l.ReasoneCode LIKE '%7%' OR l.ReasoneCode IS NULL)
GROUP BY mc.Quantity
,mc.Data
,mc.Machine
,mc.DesignSpeed
,k.Value
ORDER BY mc.Data