从两个表中选择

时间:2017-06-06 14:08:21

标签: sql sql-server

我有两张表Table ATable B

我想在两个月和2017年之间选择每个Code的总和列,其中TableA为A,TableB为B,但我希望选择TableB中的所有行作为C,其中Year = 2017没有过滤器一个月。

低于我的尝试:

enter image description here

SELECT  A.Annee as Year,  
        code_ville as Code,
        SUM(UniteVendu) AS Unit, 
        SUM(CAVendu) AS CA,  
        SUM(B.UniteVentePrev) AS Unit_P, 
        SUM(B.CAVentePrev) AS Ca_P,
        SUM(C.UniteVentePrev) AS Unit_PPP, 
        SUM(C.CAVentePrev) AS Ca_PPP
 FROM   TableA A 
   left join TableB B on A.code=B.codeP 
                     and  A.Annee=PP.Annee 
                     and A.mois =B.mois    
   left join TableB C on A.code=C.codeP 
                     and A.Annee=C.Annee 
 where  A.Annee = 2017   
 and    A.mois >= 1 
 and    A.mois <= 3  
 GROUP BY  R.Annee, 
           code_ville

但我得到的结果不正确。

1 个答案:

答案 0 :(得分:0)

我认为我理解你的要求,如果我这样做,他们实际上相当简单。最初,您需要获取YearCode组合的列表,以便您可以构建最终结果数据集,join同时加入TableA和{{1}并进行一些条件TableB计算。

请注意,我添加了一些额外的数据来显示我的方法的全部功能:

sum

输出:

-- Built test data
declare @a table([Year] int,[Month] int,Code int, Unit int, CA decimal(20,2));
declare @b table([Year] int,[Month] int,CodeP int, Unit_P int, CA_P decimal(20,0));
insert into @a values (2017,1,280,1,298259.42),(2017,1,281,0,0),(2017,2,280,1,298220.99),(2017,2,281,0,0),(2017,3,282,0,0),(2017,3,280,1,298033.09),(2017,4,280,1,298000.00);
insert into @b values (2017,1,280,1,250000),(2017,1,280,3,950000),(2017,3,281,1,250000),(2017,3,282,1,250000),(2017,6,282,1,250000);

-- Derived table to get all combinations of Year and Code across both tables
with y as
(
    select [Year]
          ,Code
    from @a
    union    -- Use of UNION ensures that a unique list is returned.
    select [Year]
          ,CodeP
    from @b
)
select y.[Year]
      ,y.Code
      ,sum(case when a.[Month] between 1 and 3 then a.Unit else 0 end) as Unit
      ,sum(case when a.[Month] between 1 and 3 then a.CA else 0 end) as CA
      ,sum(case when b.[Month] between 1 and 3 then b.Unit_P else 0 end) as Unit_P
      ,sum(case when b.[Month] between 1 and 3 then b.CA_P else 0 end) as CA_P
      ,isnull(sum(a.Unit),0) as Unit_PPP
      ,isnull(sum(a.CA),0) as CA_PPP
from y  -- Then join this list onto both tables to get the totals
    left join @a a
        on(y.[Year] = a.[Year]
            and y.Code = a.Code
            )
    left join @b b
        on(y.[Year] = b.[Year]
            and y.Code = b.CodeP
            )
group by y.[Year]
        ,y.Code
order by y.[Year]
        ,y.Code;