1

在此处输入图像描述在此处输入图像描述在加入两个表时,我执行了一个查询,但它没有正确显示第二个表数据,而是显示垃圾值..

我使用的查询是,

select p.machinenumber,
max(case when (p.shift)=1 then xxxx end) s1_xxxx,
max(case when (p.shift)=2 then xxxx end) s2_xxxx,
avg(case when (p.shift)=1 then yyyy end) s1_yyyy ,
avg(case when (p.shift)=2 then yyyy end) s2_yyyy 
from pdata p
inner  join (select  count(case when (shift)=1 and (ename)=1  then ename end) s1_wa,
count(case when (shift)=1 and (ename)=2 then errorname end) s1_we,
count(case when (shift)=2 and (ename)=1 then errorname end) s2_wa,
count(case when (shift)=2 and (ename)=2 then ename end) s2_we,
count(case when (shift)=1 and (ename)=0 then ename end) s1_merror,
count(case when (shift)=2 and (ename)=0 then ename end) s2_merror  from mstop)m
on p.mnumber=m.mnumber
where date(p.proddate)='2013-02-25'; 

请解决这个问题??

4

3 回答 3

2

您还需要返回mnumber. m.mnumber在 mstop 表的内部连接中,您还需要返回mnumber才能根据mnumber.

inner  join (select  count(case when (shift)=1 and (ename)=1  then ename end) s1_wa,
count(case when (shift)=1 and (ename)=2 then errorname end) s1_we,
count(case when (shift)=2 and (ename)=1 then errorname end) s2_wa,
count(case when (shift)=2 and (ename)=2 then ename end) s2_we,
count(case when (shift)=1 and (ename)=0 then ename end) s1_merror,
count(case when (shift)=2 and (ename)=0 then ename end) s2_merror,
     mnumber  from mstop)m
on p.mnumber=m.mnumber
于 2013-03-01T06:41:43.110 回答
1

这是因为您没有将列投影mnumber到子查询上。您需要SELECT子查询中的列名才能在连接上可见。不要忘记GROUP BY在查询中添加子句。

select  p.machinenumber,
        max(case when (p.shift)=1 then xxxx end) s1_xxxx,
        max(case when (p.shift)=2 then xxxx end) s2_xxxx,
        avg(case when (p.shift)=1 then yyyy end) s1_yyyy ,
        avg(case when (p.shift)=2 then yyyy end) s2_yyyy 
from    pdata p
        inner  join 
        (
            select  mnumber,
                    count(case when (shift)=1 and (ename)=1  then ename end) s1_wa,
                    count(case when (shift)=1 and (ename)=2 then errorname end) s1_we,
                    count(case when (shift)=2 and (ename)=1 then errorname end) s2_wa,
                    count(case when (shift)=2 and (ename)=2 then ename end) s2_we,
                    count(case when (shift)=1 and (ename)=0 then ename end) s1_merror,
                    count(case when (shift)=2 and (ename)=0 then ename end) s2_merror  
            from    mstop
            GROUP   BY mnumber
        ) m on p.mnumber=m.mnumber
where   date(p.proddate)='2013-02-25'
GROUP   BY  p.machinenumber
于 2013-03-01T06:42:14.040 回答
0

如果垃圾来自第二张桌子,请尝试LEFT JOIN代替INNER JOIN

于 2013-03-01T06:41:40.987 回答