左外连接与主表的where子句

时间:2016-05-13 04:58:46

标签: sql-server

select
   b.d,
   sum(pic_sam)/60 
from
   inter b 
left  join
   sah  
      on d=date  
where
   b.d between '01 May 2016' and '06 May 2016'  
group by
   b.d 
order by
   b.d

我写了一个像上面这样的sql脚本,它显示如下的数据

2016-05-01   00:00:00.000   NULL
2016-05-02   00:00:00.000   2608.422500
2016-05-03   00:00:00.000   20236.230333
2016-05-04   00:00:00.000   21398.398166
2016-05-05   00:00:00.000   0.000000
2016-05-06   00:00:00.000   0.000000

现在我需要在这里添加另一个条件

select
   b.d,
   sum(pic_sam)/60 
from
   inter b 
left  join
   sah  a
      on d=date  
where
   b.d between '01 May 2016' and '06 May 2016'  **and a.line_code like 'K%;**
group by
   b.d 
order by
   b.d

然后数据应该如下所示,但第二个脚本不能按照以下要求工作。

2016-05-01   00:00:00.000   NULL
2016-05-02   00:00:00.000   500.422500
2016-05-03   00:00:00.000   10000.230333
2016-05-04   00:00:00.000   5000.398166
2016-05-05   00:00:00.000   0.000000
2016-05-06   00:00:00.000   0.000000

1 个答案:

答案 0 :(得分:2)

将右表过滤器移至ON条件

SELECT b.d,
       Sum(pic_sam) / 60
FROM   inter b
       LEFT JOIN sah a
              ON d = date
                 AND a.line_code LIKE 'K%'
WHERE  b.d BETWEEN '01 May 2016' AND '06 May 2016'
GROUP  BY b.d
ORDER  BY b.d