SQL Server 2012:左连接多个选择语句

时间:2018-07-05 15:30:59

标签: sql sql-server sql-server-2012

我需要找到5月工作或6月停止工作的零售店。

我有一个类似的SQL查询:

select * 
from
    (select a.OL_id [Kod], d.Year, d.Month, OLRegion_name, OLDistrict_name, OLCntArea_name, OLCity_name, a.RM_name, a.DSM_Name, a.Supervisor_name, a.MerchName, SUM(s.SaleDal) [Sales]
    from DW_Cube_Area a
    join DW_Cube_Fact_Sale s on a.Area_Id=s.Area_Id
    join DW_Cube_Time d on d.Date_Id=s.Date_Id
    join DW_Cube_SKU p on s.SKU_Id=p.SKU_Id
    where d.Date between '20180501' and '20180531'
    and a.StartDate between '20180501' and '20180531'
    and a.PID=0 and s.PID=0
    and p.ProdGroupName Not Like 'Напої'
    and p.UnitName  Like 'кег'
    group by  d.Year, d.Month, a.OL_id, a.RM_name, a.DSM_Name, a.Supervisor_name, a.MerchName, OLRegion_name, OLDistrict_name, OLCntArea_name, OLCity_name
    having ABS(SUM(s.SaleDal))>0.1) tb1
left join
    (select a.OL_id [Kod], d.Year, d.Month, OLRegion_name, OLDistrict_name, OLCntArea_name, OLCity_name, a.RM_name, a.DSM_Name, a.Supervisor_name, a.MerchName, SUM(s.SaleDal) [Sales]
    from DW_Cube_Area a
    join DW_Cube_Fact_Sale s on a.Area_Id=s.Area_Id
    join DW_Cube_Time d on d.Date_Id=s.Date_Id
    join DW_Cube_SKU p on s.SKU_Id=p.SKU_Id
    where d.Date between '20180601' and '20180630'
    and a.StartDate between '20180601' and '20180630'
    and a.PID=0 and s.PID=0
    and p.ProdGroupName Not Like 'Напої'
    and p.UnitName  Like 'кег'
    group by  d.Year, d.Month, a.OL_id, a.RM_name, a.DSM_Name, a.Supervisor_name, a.MerchName, OLRegion_name, OLDistrict_name, OLCntArea_name, OLCity_name
    having ABS(SUM(s.SaleDal))>0.1) tb2
on 
    t1.Kod = t2.Kod
where 
    t2.Kod is null

执行此查询时,错误结果为:

无法绑定多部分标识符“ t1.Kod”。

无法绑定多部分标识符“ t2.Kod”。

为什么?

如果我将查询分为2个单独的查询,则运行正常。

2 个答案:

答案 0 :(得分:0)

我认为您可以使用条件聚合更轻松地完成您想做的事情:

select a.OL_id [Kod], d.Year, d.Month, OLRegion_name, OLDistrict_name, OLCntArea_name, OLCity_name, a.RM_name, a.DSM_Name, a.Supervisor_name, a.MerchName,
       sum(case when d.Date between '20180501' and '20180531' and a.StartDate between '20180501' and '20180531'
                then s.SaleDal else 0
           end) as sales_201805,
       sum(case when d.Date between '20180601' and '20180630' and a.StartDate between '20180601' and '20180630'
                then s.SaleDal else 0
           end) as sales_201806
from DW_Cube_Area a join
     DW_Cube_Fact_Sale s
     on a.Area_Id = s.Area_Id join
     DW_Cube_Time d
     on d.Date_Id = s.Date_Id join
     DW_Cube_SKU p
     on s.SKU_Id = p.SKU_Id
where a.PID = 0 and s.PID = 0 and
      p.ProdGroupName Not Like 'Напої' and
     p.UnitName  Like 'кег'
group by d.Year, d.Month, a.OL_id, a.RM_name, a.DSM_Name, a.Supervisor_name, a.MerchName, OLRegion_name, OLDistrict_name, OLCntArea_name, OLCity_name;

答案 1 :(得分:0)

别名应为tb1 / tb2,而不是t1 / t2

classpath 'com.android.tools.build:gradle:3.1.0',
distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip

现在一切正常。