0

我的简化查询如下所示:

 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) 的行没有出现我感谢任何尝试:-)

4

2 回答 2

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 
于 2012-05-10T16:09:51.467 回答
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'
于 2012-05-10T15:17:38.977 回答