使用Left Outer Join时输出错误

时间:2013-05-17 00:37:45

标签: sql sql-server sql-server-2008

这是我的剧本

SELECT a.PLUCODE as [Code],a.ITEMNAME as [Item],  
    sum(a.janQTY) AS [2012 QTY] ,sum(a.janAmt) AS [2012 AMT],  
    sum(b.janQTY) AS [2013 QTY] ,sum(b.janAmt) AS [ ]
FROM 2012_Table 
LEFT OUTER JOIN 2013_Table b  ON a.PLUCODE=b.PLUCODE 
WHERE a.CATEGORY='Category1'  
GROUP BY a.PLUCODE,a.ITEMNAME 
ORDER BY a.PLUCODE  

OUTPUT

Code Item     2012 QTY     2012 AMT     2013 QTY  2013 AMT  
0312 ItemOne  67           837,500      21        262,500    

我在[2012 QTY]和[2012 AMT]中的输出是正确的,但在[2013 QTY]和[2013 AMT]错误时它应该是1为数量而12,500仅为数量,有人可以帮助我什么是正确的脚本。

3 个答案:

答案 0 :(得分:1)

您正在获得笛卡尔结果。 21个条目@ 12,500 = 262,500。您可能需要根据自己的优点预先确定每个,然后左连接。我假设2013年的表与2012年的结构相同。

select
      PQ1.PLUCode,
      PQ1.Item,
      PQ1.[2012 QTY],
      PQ1.[2012 AMT],
      PQ2.[2013 QTY],
      PQ2.[2013 AMT]
   from
      ( select a.PLUCode, 
               a.ItemName as [Item],
               sum( a.JanQty ) as [2012 QTY],
               sum( a.JanAmt ) as [2012 AMT]
           from 2012_Table a
           where a.Category = 'Category1'
           group by a.PLUCode, a.ItemName
           order by a.PLUCode ) PQ1
      LEFT JOIN
      ( select b.PLUCode, 
               b.ItemName as [Item],
               sum( b.JanQty ) as [2013 QTY],
               sum( b.JanAmt ) as [2013 AMT]
           from 2013_Table b
           where b.Category = 'Category1'
           group by b.PLUCode, b.ItemName
           order by b.PLUCode ) PQ2
         ON PQ1.PLUCode = PQ2.PLUCode

答案 1 :(得分:0)

这应该更好:

SELECT 
    a.PLUCODE as [Code],
    a.ITEMNAME as [Item],  
    sum(Case When Yr=2012 Then a.janQTY Else 0 End) AS [2012 QTY],
    sum(Case When Yr=2012 Then a.janAmt Else 0 End) AS [2012 AMT],  
    sum(Case When Yr=2013 Then a.janQTY Else 0 End) AS [2013 QTY],
    sum(Case When Yr=2013 Then a.janAmt Else 0 End) AS [2013 AMT],  
FROM (
    Select 2012 As Yr, * From 2012_Table 
 UNION ALL
    Select 2013 As Yr, * From 2013_Table
      ) a  
WHERE a.CATEGORY='Category1'  
GROUP BY a.PLUCODE,a.ITEMNAME 
ORDER BY a.PLUCODE  

答案 2 :(得分:0)

因为您只是按类别过滤表A,如果跨类别重复PLUCode,您将在JOIN右侧包含所有记录和指定的PLU。要查看发生了什么,请删除SUM聚合和GROUP BY子句,然后包括A.Category和B.Category。