连接两个表

时间:2015-05-16 12:43:48

标签: sql-server join datagridview

以下是提供错误结果的SQL查询。

Select  ASXCode.Stock_Code, Count(Bought.Number_Bought) as Transactions, 
        SUM(Bought.Number_Bought) as Bought,
        SUM(Bought.Total_Cost) / SUM(Bought.Number_Bought) AS Average_Price,
        SUM(Bought.Acc_Interest) as Interest,
        SUM(Income.Total_Income) / COUNT(Bought.Number_Bought) as Derived_Income,  
        Sum(Bought.Total_Cost + Bought.Acc_Interest + Income.Neg_Total_Income) / SUM(Bought.Number_Bought) as Breakeven
FROM 
    ASXCode 
  LEFT JOIN 
    Bought ON Bought.Stockid = ASXCode.Stockid
  LEFT JOIN 
    Income ON ASXCode.Stockid = Income.Incomeid
GROUP BY 
    ASXCode.Stock_Code

上面的SQL查询导致DataGridview如下:

 Stock_Code|Transactions|Bought|Average_Price|Interest|Derived_Income| Breakeven   
      ASL         2      10000      0.45       15.00                                                                           
      RCR         2       5000      1.90       55.35   
      SKE         6      20000      1.27      148.97    1071.43        0.96 

此表有两个问题。在计算盈亏平衡价格时,总收入乘以交易数量。正确的盈亏平衡价格约为1.22。如果我可以添加“除以COUNT Number_Rows的总和”,则可以修复查询的这一部分。但是我在查询中包含它并没有成功。其次,由于其他两个持股没有收入,收入领域是空的,我认为这使得无法计算盈亏平衡价格。我认为这个问题可以通过在查询中包含“哪里收入不为空”来解决。然而,尽管在查询中包含这样的语句进行了各种尝试,但我已经画了一个空白。我真的很想能解决我的问题。

1 个答案:

答案 0 :(得分:0)

我认为您的问题来自于您拥有主表和两个详细信息表的位置:

[ Bought ] *-------1 [ ASXCode ] 1-------* [ Income ]

因此,当您需要ASXCode上的结果库并在Bought上详细说明而没有任何交叉到Income时,反之亦然;你需要这样的查询:

SELECT *
FROM ASXCode AS A
    LEFT OUTER JOIN
    (SELECT *
     FROM Bought
     GROUP BY *) AS B ON A.PK = B.FK
    LEFT OUTER JOIN
    (SELECT *
     FROM Income
     GROUP BY *) AS I ON A.PK = I.FK

所以,对于你我认为这个查询应该可以正常工作:

SELECT
    A.Stock_Code, 
    B.Count_Number_Bought as Transactions, 
    B.SUM_Number_Bought as Bought,
    B.SUM_Total_Cost / B.SUM_Number_Bought AS Average_Price,
    B.SUM_Acc_Interest as Interest,
    I.SUM_Total_Income / B.Count_Number_Bought as Derived_Income,  
    (B.SUM_Total_Cost + B.SUM_Acc_Interest + I.SUM_Neg_Total_Income) / B.SUM_Number_Bought as Breakeven
FROM 
    ASXCode AS A
  LEFT JOIN 
    (SELECT 
         Bought.Stockid,
         COUNT(Bought.Number_Bought) As COUNT_Number_Bought,
         SUM(Bought.Number_Bought) AS SUM_Number_Bought,
         SUM(Bought.Total_Cost) AS SUM_Total_Cost,
         SUM(Bought.Acc_Interest) AS SUM_Acc_Interest
     FROM 
         Bought 
     GROUP BY 
         Bought.Stockid) AS B ON B.Stockid = A.Stockid
  LEFT JOIN
    (SELECT 
         Income.Stockid,
         SUM(Income.Total_Income) AS SUM_Total_Income,
         SUM(Income.Neg_Total_Income) AS SUM_Neg_Total_Income
     FROM
         Income 
     GROUP BY
         Income.Stockid) AS I ON A.Stockid = I.Stockid