对于这两个表:Product(ProductID,ProductName),Sales(SalesOrderID,ProductID,SaleDate) -

时间:2015-11-05 06:06:07

标签: sql-server

对于这两个表:

  

产品(ProductID,ProductName)

     

销售(SalesOrderID,ProductID,SaleDate)

  • 获取去年销售的产品清单。获取

  • 列表
  • 去年未售出的产品。

2 个答案:

答案 0 :(得分:-1)

去年出售

select Product.ProductName from Product inner join Sales on Product.ProductID = Sales.ProductID where year(Sales.SaleDate) = year(getdate())-1

去年没有出售

select Product.ProductName from Product where ProductID not in ( select ProductID in Sales where year(Sales.SaleDate) = year(getdate())-1)

答案 1 :(得分:-1)

以下是SARG能够提供的优选解决方案:

select distinct p.ProductID, p.ProductName 
from Product p
join Sales s on p.ProductID = s.ProductID
where s.SaleDate >= cast (cast(year(getdate()) as varchar(8)) + '0101' as date)

select distinct p.ProductID, p.ProductName 
from Product p
left join Sales s on p.ProductID = s.ProductID
             and s.SaleDate >= cast (cast(year(getdate()) as varchar(8)) + '0101' as date)
where s.ProductID is null