连接表时的SQL(没有销售的月份和子文本)

时间:2013-11-25 06:34:00

标签: sql derby

DBMS:Derby Embedded 您好我想知道如何能够取得像

这样的结果
SubTextureID Year Month NetSales
1            2013 10    1000
2            2013 10    2000
3            2013 10    0

如果该产品,第三行永远不会出现 订单明细表中没有销售(没有记录) 任何帮助将不胜感激! 谢谢 千斤顶

   select  s.TextureName, s.SubTextureId,  sum(COALESCE(d.NetSales, 0)) NetSales
    from    (select SubTextureId, TextureName from subtexture) as s
    join
            (select SubTextureId, ProductCode from products) as p
        on  (p.SubTextureId = s.SubTextureId)
    left outer join
            (select ProductCode, OrderCode, NetSales from order_details) as d
        on  (d.ProductCode = p.ProductCode)
    left outer join
            (   select  YEAR(o.PurchaseDateTime) y,
                        MONTH(o.PurchaseDateTime) m,
                        OrderCode
                from    orders o
                where   o.PurchaseDateTime between '2013-11-01 00:00:00' and '2013-11-30 23:59:59' -- make use of an index if one exists
            ) as o
        on  (o.orderCode = d.orderCode)
    group by s.TextureName, s.SubTextureId, o.y, o.m

1 个答案:

答案 0 :(得分:0)

因为您使用了LEFT OUTER JOIN,请尝试使用RIGHT OUTER JOIN,如果您了解LEFTRIGHT OUTER JOIN之间的区别,您将处理问题