group by子句中的错误

时间:2018-06-28 12:17:35

标签: sql database

在我的数据库中使用group by子句方法时出现错误。这是我的代码:

using (OleDbConnection objConn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FileName + @";Extended Properties=""Excel 12.0;IMEX=1;HDR=YES;"""))
                {
                    objConn.Open();

}

这是我得到的错误:

SELECT A.dvdID  AS 'DVD ID',
A.memberID AS 'MEMBER ID',
B.first_name AS 'FIRST NAME',
B.last_name AS 'LAST NAME',
A.branchID AS 'BRANCH ID',
COUNT(A.dvdID) AS 'Total DVDs Borrowed'
FROM RENT A
JOIN MEMBER B ON (B.memberID = A.memberID)
WHERE A.date_returned = NULL
GROUP BY  A.memberID
ORDER BY last_name ASC;

我在哪里做错了?

3 个答案:

答案 0 :(得分:1)

您应将查询编写为:

SELECT r.memberID,
       m.first_name, m.last_name, r.branchID,
       COUNT(r.dvdID) AS "Total DVDs Borrowed"
FROM RENT r JOIN
     MEMBER m
     ON m.memberID = r.memberID
WHERE r.date_returned IS NULL
GROUP BY r.memberID, m.first_name, m.last_name, r.branchID
ORDER BY last_name ASC;

注意:

  • SELECT中所有未聚合的列都应位于GROUP BY中(这是您的明显错误)。
  • 表别名应代表它们代表的表,而不是任意字母。
  • 仅对字符串和日期常量使用单引号。请勿将它们用作列别名。
  • DVDidSELECT中毫无意义(您的查询将它们计算在内),因此我将其删除。
  • = NULL过滤所有行。正确的SQL语法为IS NULL

答案 1 :(得分:0)

如果group by子句中不存在选择列表中的列,则只能在聚合函数中使用它。 如果仍然需要将计数与dvdID一起使用,则使用Partition By子句,并假设您使用的是sql-server。

SELECT A.dvdID  AS 'DVD ID',
A.memberID AS 'MEMBER ID',
B.first_name AS 'FIRST NAME',
B.last_name AS 'LAST NAME',
A.branchID AS 'BRANCH ID',
COUNT(A.dvdID) OVER (PARTITION BY A.memberID) AS 'Total DVDs Borrowed'
FROM RENT A
JOIN MEMBER B ON (B.memberID = A.memberID)
WHERE A.date_returned = NULL
ORDER BY last_name ASC

答案 2 :(得分:0)

group by的另一种替代方法是仅查询未归租金的数量,并将其加入会员列表

select
      m.first_name AS 'FIRST NAME',
      m.last_name AS 'LAST NAME',
      r.BranchID as 'BRANCH ID',
      r.DVDsBorrowed as 'Total DVDs Borrowed'
   from
      ( select MemberID, 
               BranchID, 
               count(*) DVDsBorrowed
           from 
              rent
           WHERE 
              date_returned IS NULL
           group by 
              MemberID, 
              BranchID ) r
         JOIN Member m
            on r.MemberID = m.MemberID

如果您实际上还有一个额外的分支查找表并需要该描述,则可以向联接中添加类似内容,并将分支标题添加至字段列表中

   JOIN Branch b
      on r.BranchID = b.BranchID