这是SQL Server数据库
第一个表Product表,字段有:ProductId ProductName
第二表ProductSKU表,字段有:ProductId SKU ReleaseDate
他们是一对多的关系
即一个Product可以有多个SKU,但至少有一个现在要解决的问题是:
当向product表加入一条数据的时候,也向ProductSKU表加入了一条数据
但日后会不断为一个Product再添加SKU,也就出现了一个Product有多个SKU我想提取最新的10条含有至少2个SKU的Product信息
---------------------------------------------
并且排序方式是按照ProductSKU表的ReleaseDate字段进行排序请问如何写这个SQL语句?

解决方案 »

  1.   

    select a.ProductId,a.ProductName,count(b.ProductId)
    from Product a
    inner join ProductSKU b
    on a.ProductId = b.ProductId
    where count(b.ProductId)> 2
    order by b.ReleaseDate DESC
      

  2.   

    上面的错了吧,where里面好像是不能用聚合函数的吧
      

  3.   

    select top 10 a.ProductName
    from Product  a , 
     (select count(*) as num,a.ProductId
      from Product a,ProductSKU b
      where  a.ProductId = b.ProductId  
      group by  a.ProductId
      )  b,ProductSKU c
    where a.ProductId = b.ProductId  and a.ProductId = c.ProductId and b.num > 2
    order by c.ReleaseDate DESC不是最优,但是应该没有错,我没有测试,要是错了,就不好意思了.;)
      

  4.   

    select a.ProductId, a.ProductName, b.SKU, count(b.ProductId),max(ReleaseDate)
    from Product a
    inner join ProductSKU b
    on a.ProductId = b.ProductId
    group by a.ProductId, a.ProductName, b.SKU
    having count(b.ProductId)> 2
    order by max(ReleaseDate) DESC这个写法应该是比较标准的,参考一下
      

  5.   

    同时不要求提取重复的Product表信息
      

  6.   

    实际上我只是需要提取Product表的信息ProductId ProductName字段
    只是根据ProductSKU表中一个product对应大于2个SKU的最新方式进行获取所以不可以出现重复的Product信息