两次加入同一张桌子

时间:2014-11-05 00:57:46

标签: sql join duplicates

我坚持使用连接,我尝试连接同一个表两次。

   CREATE TABLE [dbo].[Accounts](  
   [Account] [nvarchar](10) NULL,  
   [Value] [real] NULL,  
   [Period] [nvarchar](8) NULL)   

  INSERT INTO [dbo].[Accounts] VALUES ('AC1', 100, '201407')  
  INSERT INTO [dbo].[Accounts] VALUES ('AC2', -100, '201407')  
  INSERT INTO [dbo].[Accounts] VALUES ('AC3', 200, '201407')  
  INSERT INTO [dbo].[Accounts] VALUES ('AC4', -200, '201407')  
  INSERT INTO [dbo].[Accounts] VALUES ('AC1', 100, '201408')  
  INSERT INTO [dbo].[Accounts] VALUES ('AC1', -100, '201408')  
  INSERT INTO [dbo].[Accounts] VALUES ('AC2', 200, '201408')  
  INSERT INTO [dbo].[Accounts] VALUES ('AC2', -200, '201408')  
  INSERT INTO [dbo].[Accounts] VALUES ('AC5', 100, '201407')  
  INSERT INTO [dbo].[Accounts] VALUES ('AC5', -100, '201407')  
  INSERT INTO [dbo].[Accounts] VALUES ('AC6', 200, '201408')  
  INSERT INTO [dbo].[Accounts] VALUES ('AC6', -200, '201408')  
  INSERT INTO [dbo].[Accounts] VALUES ('AC3', 200, '201408')  
  INSERT INTO [dbo].[Accounts] VALUES ('AC3', -200, '201408')  
  INSERT INTO [dbo].[Accounts] VALUES ('AC7', 300, '201408')  
  INSERT INTO [dbo].[Accounts] VALUES ('AC8', -300, '201408')  

我尝试归档的第一个结果是在第一列中包含所有帐户,在每个单独的列中包含每个Period的值。我尝试了很多不同的连接,没有任何工作。我的最后一个是下面但它在第一个时期复制了我的一些记录,并没有显示一些帐户。

  SELECT A1.account, A1.value, A2.value FROM Accounts A1   
  FULL OUTER JOIN accounts A2 on A1.account = A2.account  
  WHERE A1.Period = '201407' and A2.period = '201408'

我尝试归档的最终查询应该会产生这样的结果:

ACCOUNT P1    P2  
AC1     100   0  
AC2     -100  0  
AC3      200  0  
AC4     -200  NULL  
AC5      0    NULL  
AC6      0    0
AC7     NULL  300
AC8     NULL  -300

我做错了什么?我尝试了所有可能的连接类型并且选择了:(。

非常感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

Tom,连接不需要达到您正在寻找的结果。请尝试以下代码:

select account
    ,P1=sum(case when period = '201407' then value else null end)
    ,P2=sum(case when period = '201408' then value else null end)
from Accounts
where period in ('201407', '201408')
group by account

答案 1 :(得分:0)

感谢您的快速回答。 它正在工作:)

与此同时,我发现另一种解决方案也在起作用。 分析你的我认为它比我的效率更高。

谢谢!

select distinct(x.account) konto, a.v1, b.v2 from accounts X 
left join(select account a1, sum(value) v1 from accounts  where Period = '201407' group by account) a on a.a1 = x.account
left join(select account a2, sum(value) v2 from accounts  where Period = '201408' group by account) b on b.a2 = x.account