我无法添加条件,只显示出勤率低于81的人。
SELECT Absence.StudentID AS StudentNumber,
Student.NAME AS "Student Name",
Subject.NAME AS "Subject Name",
CONVERT(VARCHAR, 100 - (100 * count(*) / 10)) AS 'Attendance(%)'
FROM Absence,
Subject,
Student,
(
SELECT COUNT(*) AS tot
FROM Absence
) x
WHERE Subject.SubjectCode = Absence.SubjectCode
AND Student.StudentNumber = Absence.StudentID
GROUP BY Absence.StudentID,
Subject.NAME,
Student.NAME;
以上是完全显示我想要的代码,但我不能仅添加条件。我的出勤率(%)已经是正确的吗?所以使用CAST或CONVERT也不起作用。它说转换有问题。
答案 0 :(得分:1)
这是数学中的隐式数据类型转换
select
100/50 as intMath
, 100.00/50.00 as nbrMath
答案 1 :(得分:1)
当试图获得百分比时,它会乘以100并且是DECIMAL,这似乎不是代码的工作方式:
SELECT (CAST(9 AS DECIMAL(5,2))/CAST(10 AS DECIMAL(5,2)))*CAST(100 AS DECIMAL(5,2))
-- Returns 90.00
SELECT (CAST(9 AS INT)/CAST(10 AS INT))*CAST(100 AS INT)
-- Returns 0
使用您的OP示例:
SELECT CAST(100 AS DECIMAL(5,2)) - ((CAST(100 AS DECIMAL(5,2)) * CAST(8 AS DECIMAL(5,2))) / CAST(10 AS DECIMAL(5,2)))
-- Returns 20.00
-- Formatted with a percent:
SELECT SUBSTRING(CAST(CAST(100 AS DECIMAL(5,2)) - ((CAST(100 AS DECIMAL(5,2)) * CAST(8 AS DECIMAL(5,2))) / CAST(10 AS DECIMAL(5,2))) AS VARCHAR(25)),1,5) + '%'
注意:这适用于SQL Server
。 90%是.9,当它是CAST AS INT
时被视为0。