关于连接的SQL查询

时间:2012-04-18 13:45:51

标签: sql sql-server

我有两张表mem_loan和分享。在mem_loan表中,我有一个名为DATE的列,在共享中我有一个名为noofshares的列。没有mem_loan的主键是共享表中的外键。我想使用以下查询,但收到错误。

SELECT SUM(noofshares),year(convert(datetime,mem_loan.dos,105)) 
FROM shares s,mem_loan ml 
JOIN mem_loan ON mem_loan.loan_acno = shares.loan_acno 
WHERE year(convert(datetime,dos,105))=year(getdate())

,错误如下:

  

列'mem_loan.DOS'在选择列表中无效   因为它不包含在聚合函数中   或GROUP BY子句。

请帮帮我

6 个答案:

答案 0 :(得分:4)

如错误消息所示,您需要GROUP BY未包含在聚合函数中的列。

但是,您的示例SQL似乎也有其他错误。特别是,您已将mem_loan表包含两次但仅包含一个连接条件,因此将执行交叉连接。这不是你的意思。

答案 1 :(得分:1)

试试这个

SELECT SUM(noofshares),year(convert(datetime,mem_loan.dos,105)) 
FROM shares s,mem_loan ml JOIN mem_loan ON mem_loan.loan_acno=shares.loan_acno 
where year(convert(datetime,dos,105))=year(getdate()) 
group by year(convert(datetime,mem_loan.dos,105)) 

答案 2 :(得分:0)

这样的事情:

SELECT 
  SUM(noofshares),
  year(convert(datetime,mem_loan.dos,105)) 
FROM 
  shares s,mem_loan ml 
  JOIN mem_loan ON mem_loan.loan_acno=shares.loan_acno 
where year(convert(datetime,dos,105))=year(getdate())
GROUP BY year(convert(datetime,mem_loan.dos,105))

或者你可以这样做:

SELECT
    t.noofshares,
    SUM(t.LoanYear)
FROM
    (
        SELECT 
          noofshares,
          year(convert(datetime,mem_loan.dos,105)) as LoanYear
        FROM 
          shares s,mem_loan ml 
          JOIN mem_loan ON mem_loan.loan_acno=shares.loan_acno 

    ) AS t
where 
    t.LoanYear=year(getdate())
GROUP BY
    t.LoanYear

答案 3 :(得分:0)

你必须:

GROUP BY year(convert(datetime,dos,105))

让您的聚合SUM()正常工作

答案 4 :(得分:0)

问题是您正在尝试使用Sum函数进行聚合,并且sql server不知道要在mem_loan表中使用哪个年份记录。

对于初学者来说,选择聚合年份的函数(即MIN):

SELECT 
    SUM(noofshares),
    MIN(year(convert(datetime,mem_loan.dos,105))) 
FROM
    shares s,
    mem_loan ml 
JOIN mem_loan ON mem_loan.loan_acno=shares.loan_acno 
WHERE 
    year(convert(datetime,dos,105))=year(getdate())

答案 5 :(得分:0)

您可以使用OVER来排除必须将列dos作为汇总的一部分。 免责声明:我没有管理工作室与我一起测试:

   SELECT SUM(noofshares) OVER (PARTITION BY year(convert(datetime,mem_loan.dos,105)) ),year(convert(datetime,mem_loan.dos,105)) 
FROM shares s,mem_loan ml 
JOIN mem_loan ON mem_loan.loan_acno = shares.loan_acno 
WHERE year(convert(datetime,dos,105))=year(getdate())

有关OVER的更多信息:http://msdn.microsoft.com/en-us/library/ms189461.aspx