0

我有两个 sql 查询

第一个查询:我得到了除与日期相关的详细信息之外的所有详细信息

SELECT  att.roll_no  AS `att_roll_no`,att.full_name,att.st_class,att.st_section,
SUM(att.hasAttended= 'P') AS DaysPresent, 
SUM(att.hasAttended= 'A') AS DaysAbsent, 
COUNT(DISTINCT att.att_date) AS WorkingDays,
COUNT(*) AS totalClasses
FROM     attendance as att
WHERE att.st_class = 1 AND att.st_section = 'A' 
GROUP BY att.roll_no

上述查询的输出表如下:

在此处输入图像描述

第二个查询:我只得到与日期相关的详细信息

SELECT  hasAttended, att_date  FROM attendance
WHERE st_class = 1 AND st_section = 'A' AND att_date = 'Tue Apr 02 2013'
GROUP BY roll_no

上述查询的输出表如下:

在此处输入图像描述

现在我需要将上面的两个表连接到一个表中。

我尝试过的

在结果查询中,我使用的是 INNER JOIN。它如下:

SELECT
  att_outer.hasAttended,
  att_outer.att_date
FROM
  attendance AS att_outer
  INNER JOIN(
    SELECT 
      att.roll_no  AS `att_roll_no`,
      att.full_name,
      att.st_class,att.st_section,
      SUM(att.hasAttended= 'P') AS DaysPresent, 
      SUM(att.hasAttended= 'A') AS DaysAbsent, 
      COUNT(DISTINCT att.att_date) AS WorkingDays,
      COUNT(*) AS totalClasses
    FROM 
      attendance as att
    WHERE
      att.st_class = 1
      AND att.st_section = 'A' 
    GROUP BY att.roll_no
  )att ON att_outer.roll_no = att.roll_no
WHERE 
  att_outer.st_class = 1
  AND att_outer.st_section = 'A'
  AND att_outer.att_date = 'Tue Apr 02 2013'
GROUP BY roll_no

但我收到以下错误:

#1054 - Unknown column 'att.roll_no' in 'on clause'

请让我知道结果查询是否正确。另外加入我使用的是正确与否。

谢谢。

4

3 回答 3

2

您想加入 ALIAS 名称,别名为att_roll_no

改变:

 ON att_outer.roll_no = att.roll_no

ON att_outer.roll_no = att_roll_no
于 2013-04-07T12:38:25.647 回答
1

您在 select 子句中没有名为 roll_no 的列,因此您无法对此进行连接,因此出现错误:att.roll_no。

于 2013-04-07T12:37:12.517 回答
1

您在内部查询中提供了该列的别名。您应该使用该别名,因为该列不再可见。

SELECT  att_outer.hasAttended, 
        att_outer.att_date,
        att.full_name,
        att.st_class,
        att.st_section,
        att.DaysPresent,
        att.DaysAbsent,
        att.WorkingDays,
        att.totalClasses
FROM    attendance AS att_outer
        INNER JOIN
        (
            SELECT  att.roll_no  AS `att_roll_no`,
                    att.full_name,
                    att.st_class,
                    att.st_section,
                    SUM(att.hasAttended= 'P') AS DaysPresent, 
                    SUM(att.hasAttended= 'A') AS DaysAbsent, 
                    COUNT(DISTINCT att.att_date) AS WorkingDays,
                    COUNT(*) AS totalClasses
            FROM    attendance as att
            WHERE   att.st_class = 1 AND 
                    att.st_section = 'A' 
            GROUP   BY att.roll_no
        )att ON att_outer.roll_no = att.att_roll_no
WHERE   att_outer.st_class = 1 AND 
        att_outer.st_section = 'A' AND 
        att_outer.att_date = 'Tue Apr 02 2013'
于 2013-04-07T12:39:33.840 回答