Matching data from three tables in Sql Server 2008

后端 未结 1 1889
我在风中等你
我在风中等你 2021-01-27 05:54

I have three tables Despatch, Activation and Replaced as below:

\"enter

相关标签:
1条回答
  • 2021-01-27 06:44

    I think you could use left joins to do this. Try this query, with your sample data it produces the desired output, except for the ApprovedQty, but I don't get how you arrived at 12 for that with the sample data:

    select 
        d.LOTQty, 
        ApprovedQty = count(d.ProductNo),
        d.DispatchDate,
        Installed = count(a.ProductNo) + count(r.ProductNo)
    from 
        Despatch d 
    left join 
        Activation a 
         on d.ProductNo = a.ProductNo 
        and d.DispatchDate < a.ActivationDate 
        and d.LOTQty = a.LOTQty
    left join 
        Replaced r 
          on d.ProductNo = r.ProductNo 
         and d.DispatchDate < r.RecordDate
         -- only count Replaced when there is no match in Activation
         -- or DispatchDate is greater then ActivationDate
         and (a.ActivationDate is null or a.ActivationDate < d.DispatchDate)
    where 
        d.LOTQty = 20
    group by 
        d.LOTQty, d.DispatchDate
    

    this would output:

    LOTQty  ApprovedQty DispatchDate    Installed
    20      6           2013-08-07      5
    
    0 讨论(0)
提交回复
热议问题