0

我有两张表 mem_loan 和 share。在 mem_loan 表中,我有一个名为 DATE 的列,在份额中,我有一个名为 noofshares 的列。没有 mem_loan 的主键是 share 表中的外键。我想使用以下查询,但出现错误。

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 子句中。

请帮帮我

4

6 回答 6

4

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

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

于 2012-04-18T13:47:32.780 回答
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)) 
于 2012-04-18T13:48:06.760 回答
0

你必须:

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

让您的汇总 SUM() 工作

于 2012-04-18T13:48:51.940 回答
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

于 2012-04-18T14:18:23.810 回答
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
于 2012-04-18T13:48:27.477 回答
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())
于 2012-04-18T13:52:39.477 回答