1

我有关注表stuinfo

+------------+-------+-----------+
|   Roll_no  | Name  | Lastname  |
+------------+-------+-----------+
|   37032    | johny | bravo     |
|   37034    |  sam  | smith     |
+------------+-------+-----------+

第二个stu_attendace

+------------+-------+-----------+
|   Roll_no  | Name  | month     |
+------------+-------+-----------+
|   -1       | total |   26      |
|   37032    | johny |   19      |
|   37034    |  sam  |   25      |
+------------+-------+-----------+

总天数为 26 天,因此 johny 的出勤率为 73.03% , Sam 的出勤率为 95.03% 。

那么如何通过在运行时计算并在实际上不在数据库中的新列“per_attendace”中显示这些值来显示他们的出勤率。如下图所示

+----------+--------+-----------+---------------+
|  roll_no |  name  | last_name | per_attendace |
+----------+--------+-----------+---------------+
|  37032   |  johny | bravo     |  xx %         |
|  37034   |  sam   | smith     |  xx %         |
+----------+--------+-----------+---------------+
4

3 回答 3

2

您可以轻松地做您想做的事,在SELECT子句中您可以选择文字值、列名或任何有效的表达式。

只是JOIN这两个表,然后像这样计算百分比:

SELECT 
  i.roll_no,
  i.name,
  i.Lastname,
  ((a.month / 26) * 100) AS percent
FROM stuinfo AS i
INNER JOIN stu_attendance AS a ON i.Roll_no = a.Roll_no;

注意:

  • 无需在两个表中复制列名,只需将其从另一个表中删除,并保持您的表规范化

  • 不要像这样将总值存储为列中的值。


更新:

如果要从数据库中选择总计的值,可以这样做:

SELECT 
  i.roll_no,
  i.name,
  i.Lastname,
  ((a.month / (SELECT month 
               FROM stu_attendace
               WHERE name = 'total')) * 100) AS percent
FROM stuinfo AS i
INNER JOIN stu_attendance AS a ON i.Roll_no = a.Roll_no;

您还可以将该总值设置为变量而不是相关子查询,如下所示:

SET @total = 0;

SELECT month 
FROM stu_attendace
WHERE name = 'total'
INTO @total;

然后:

SELECT 
  i.roll_no,
  i.name,
  i.Lastname,
  ROUND(((a.month / @total) * 100), 2) AS percent
FROM stuinfo AS i
INNER JOIN stu_attendace AS a ON i.Roll_no = a.Roll_no;

我使用该ROUND函数将数字四舍五入到只有两个十进制值。

于 2013-10-08T11:08:56.210 回答
1

尝试这个

select a.roll_no , a.name ,a.last_name,(b.month/26)*100 as  per_attendace 
from stuinfo as a join 
stu_attendace as b on a.roll_no=b.roll_no
于 2013-10-08T11:09:57.673 回答
0

尝试

SELECT i.roll_no, i.name, i.Lastname, ((a.month / 26) * 100) AS percent
  FROM stuinfo AS i
 INNER JOIN stu_attendance AS a ON i.Roll_no = a.Roll_no;
于 2013-10-08T11:18:24.293 回答