【问题标题】:Two right joins / right + outer join, etc not working两个右连接/右 + 外连接等不起作用
【发布时间】:2015-05-01 23:52:58
【问题描述】:

我有 3 张桌子:

销售员表(包含所有销售员 ID 号及其姓名)、周数表(仅包含 53 个编号条目的表)和包含所有销售额的销售数据表。

我需要所有推销员的输出,所有周,即使是 0。我可以获得所有周或所有推销员的列表,但不能同时获得两者。

这是我目前所拥有的:

SELECT
DATEPART(wk, d1.u_date) as 'Week', 
d4.week AS 'AllWeeks',
convert(decimal,d1.U_slsm) as 'Salesman', 
S1.SalesmanNum   

from [test].[dbo].[@ORDERLOG] D1
right outer join [test].[dbo].[@weekcounter] d4 on (d4.week = DATEPART(wk, d1.u_date) and DATEPART(yy, d1.u_date) > 2014)
full outer join (select salesmannum from EXECUTIVE...Salesman) S1 on convert(decimal,d1.U_slsm) = S1.salesmannum 

order by d4.Week, S1.SalesmanNum 

这给了我所有 53 周的时间,即使没有销售(期望),它给了我所有每周都有销售的推销员(期望),但它只给了我所有没有销售的推销员的一个实例有销售。我每周都需要所有的推销员。 20 个推销员,53 周,1060 个结果。我究竟做错了什么?还是有更好的方法来做到这一点?

这最终将包括销售数据,但到目前为止我还不能完成这么多工作......

我尝试了很多连接组合都无济于事...... 这是在 MSSQL 2008 R2 中。

【问题讨论】:

    标签: sql sql-server-2008


    【解决方案1】:

    如果您想要销售员和周数的所有组合,您可以在表格之间使用cross join 来生成两组的笛卡尔积。

    您的查询将如下所示(根据需要调整源表名称):

    SELECT
        DATEPART(wk, d1.u_date) as 'Week', 
        all_salesman_weeks.week AS 'AllWeeks',
        convert(decimal,d1.U_slsm) as 'Salesman', 
        all_salesman_weeks.SalesmanNum   
    from (
      select * from 
      EXECUTIVE...Salesman 
      cross join 
      [test].[dbo].[@weekcounter]
    ) all_salesman_weeks
    left join [test].[dbo].[@ORDERLOG] D1 
        on (all_salesman_weeks.week = DATEPART(wk, d1.u_date) and DATEPART(yy, d1.u_date) > 2014)
        and convert(decimal,d1.U_slsm) = all_salesman_weeks.salesmannum 
    order by all_salesman_weeks.Week, all_salesman_weeks.SalesmanNum 
    

    【讨论】:

    • 非常感谢。这就是答案。现在我必须去了解“交叉连接”并找出它的工作原理......
    猜你喜欢
    • 1970-01-01
    • 2017-08-04
    • 1970-01-01
    • 2010-09-16
    • 2014-02-24
    • 2015-01-11
    • 1970-01-01
    • 1970-01-01
    • 2013-09-15
    相关资源
    最近更新 更多