2015-06-03 55 views
-1

我有2个表:在SQL SERVER “NOT IN” 的替代

  1. 百货商店表(保存百货商店的数据):

enter image description here

  • AccDocSales表(由系由令保存数据):
  • enter image description here

    现在,我想选择这些部门,它不会在每个MONTH的AccDocSales表中显示(这意味着哪个部门每个MONTH的AccDocSales表中没有DeptCode)。

    EX(这种情况下):

    enter image description here

    我用这个查询:此查询

    SELECT distinct MONTH(DocDate) as THANG, B20Dept.Code, B20Dept.Name 
    FROM B20Dept, B30AccDocSales S1 
    WHERE YEAR(S1.DocDate) = 2014 AND B20Dept.Code NOT IN 
    (
        SELECT S2.DeptCode 
        FROM B30AccDocSales S2, B20Dept 
        WHERE YEAR(S2.DocDate) = 2014 AND S2.DeptCode = B20Dept.Code 
        AND MONTH(S1.DocDate) = MONTH(S2.DocDate) 
    ) 
    ORDER BY MONTH(DocDate) 
    

    它的工作,但我的老师说: “NOT IN” 是不是可以接受的。他问我找到另一种方法来做到这一点,没有“IN”,“NOT IN”。

    PS:我发现这个查询还有一个问题。这是哪个月在“DeptCode”中的所有部门,哪个月没有行,它们在运行该查询时都不会显示任何结果。

    请帮忙。

    +0

    简单'JOIN'可以做。 –

    +2

    尝试使用“不存在”。 –

    +6

    看到那里:http://sqlperformance.com/2012/12/t-sql-queries/left-anti-semi-join –

    回答

    1

    尝试这种解决方案:

    select s.*, d.* 
    from B20Dept d 
        cross apply (select distinct YEAR(s.DocDate) Y, MONTH(s.DocDate) THANG from B30AccDocSales s) s 
        left join (
         select YEAR(s.DocDate) Y, MONTH(s.DocDate) THANG, s.DeptCode 
         from B30AccDocSales s 
         group by YEAR(s.DocDate), MONTH(s.DocDate), s.DeptCode) m on m.Y = s.Y and m.THANG = s.THANG and m.DeptCode = d.Code 
    where m.DeptCode is null 
    order by s.Y, s.THANG 
    

    编辑: 在下面的查询中,你可以找到解决问题的办法,那就是在你PS:

    declare @Year int = 2014 
    select s.*, d.* 
    from B20Dept d 
        cross apply (values (1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (11), (12)) s (THANG) 
        left join (
         select MONTH(s.DocDate) THANG, s.DeptCode 
         from B30AccDocSales s 
         where YEAR(s.DocDate) = @Year 
         group by MONTH(s.DocDate), s.DeptCode) m on m.THANG = s.THANG and m.DeptCode = d.Code 
    where m.DeptCode is null 
    union 
    select MONTH(s.DocDate) THANG, '', '' 
    from B30AccDocSales s 
    where YEAR(s.DocDate) = @Year 
    group by MONTH(s.DocDate) 
    having COUNT(distinct s.DeptCode) = (select count(1) from B20Dept) 
    order by s.THANG 
    
    +0

    谢谢。但是在一个月中,完整部门和一个月不会显示在B30AccDocSales中,两者都不会显示在查询结果中(与我的查询相同)。 –

    +0

    我编辑我的答案,以满足您的最后requeriments。 –

    +0

    它工作。非常感谢。 –