外连接内的条件?

时间:2012-05-10 15:04:07

标签: sql sql-server sql-server-2008

我的简化查询如下:

 SELECT p.product_Id,
       p.productName,
       s.LastSales_date
FROM products as p 
            LEFT OUTER JOIN
 (  SELECT product_id , 
           max(Sales_date) as LastSales_date  
          FROM Sales group by product_id) as s
on s.product_id=p.product_Id 
where  
  (s.LastSales_date is null or  -- is it right? 
  s.LastSales_date between '2012/01/01' and '2012/01/05') 

结果:

ProductName       LastSalesDate  
   p_A             2012/01/01
   p_C             2012/01/01
   p_E             2012/01/02

但是有一行错过,那行没有sales_date,所以,如何获得如下结果:

ProductName       LastSalesDate  
   p_A             2012/01/01
   p_b             <null>
   p_C             2012/01/01
   p_E             2012/01/02

我的问题是没有出现带(null)的行 我很感激任何尝试: - )

2 个答案:

答案 0 :(得分:2)

使用外连接时,务必记住从连接本身过滤外侧数据,否则会产生有效的内连接。

SELECT p.product_Id,
       p.productName,
       s.LastSales_date
FROM products as p 
LEFT OUTER JOIN
 (
   SELECT product_id , 
          max(Sales_date) as LastSales_date  
     FROM Sales 
    group by product_id
 ) as s
on s.product_id = p.product_Id 
-- Filter s here
and s.LastSales_date between '2012/01/01' and '2012/01/05'

在这种情况下,您可以使用HAVING:

过滤聚合本身
SELECT p.product_Id,
       p.productName,
       s.LastSales_date
FROM products as p 
LEFT OUTER JOIN
 (
   SELECT product_id , 
          max(Sales_date) as LastSales_date  
     FROM Sales 
    group by product_id
-- Filter max(Sales_date) here
   having max(Sales_date) between '2012/01/01' and '2012/01/05'
 ) as s
on s.product_id = p.product_Id 

答案 1 :(得分:1)

我期待你提到的结果,但如果你发现它不起作用,我建议使用COALESCE。

...也许

SELECT
p.product_Id
, p.productName
, COALESCE(s.LastSales_date,'')
FROM
products p 
LEFT OUTER JOIN
    (SELECT
        product_id
        , MAX(Sales_date) AS LastSales_date  
    FROM
        Sales
    GROUP BY
        product_id
    )  s on s.product_id = p.product_Id 
WHERE  
COALESCE(s.LastSales_date,'')  = ''
OR
COALESCE(s.LastSales_date,'') BETWEEN  '2012/01/01' and '2012/01/05'