语法错误附近,和)

时间:2017-04-19 08:22:20

标签: sql-server

这是我的查询,但在最后一行返回错误")"和第3行","

select (present/total)*100 from( 
    (select count(Staff_Att_Status) from vu_StaffInfo where Staff_Att_Status='Present' group by DHIS_Code) as present,
    (select count(Staff_Att_Status) from vu_StaffInfo group by DHIS_Code) as total
    ) as "result"

3 个答案:

答案 0 :(得分:1)

select (present/total)* 100.00   --<-- Also use decimal here to get % values like 0.01 
FROM( 
    SELECT   --<-- You need a select key word here 
          (select count(Staff_Att_Status) from vu_StaffInfo where Staff_Att_Status='Present' group by DHIS_Code) as present,
          (select count(Staff_Att_Status) from vu_StaffInfo group by DHIS_Code) as total
    ) as "result"

答案 1 :(得分:1)

试试这个..

select (present/total)*100 "result" from 
    (select count(Staff_Att_Status) from vu_StaffInfo where Staff_Att_Status='Present' group by DHIS_Code) as present,
    (select count(Staff_Att_Status) from vu_StaffInfo group by DHIS_Code) as total

您正在尝试对外部查询进行别名处理,而外部查询不能用作内部别名。

答案 2 :(得分:0)

你可能正在寻找这样的东西:(我已将你的subquerys改为CTE,因为它们的结果很容易阅读和理解)

with present
as (
  select DHIS_Code, count(*) as count 
  from vu_StaffInfo where Staff_Att_Status='Present' 
  group by DHIS_Code
),

with total
as (
  select DHIS_Code, count(*) as count 
  from vu_StaffInfo 
  group by DHIS_Code
)

select total.DHIS_Code, (isnull(present.count,0) / total.count) * 100.00
from total
     left outer join present on present.DHIS_Code = total.DHIS_Code

您可能希望每个DHIS_Code返回一个百分比,看到您正在按照它进行分组。

此外,我已经通过count(*)更改了计数(Staff_Att_Status),因为您需要这些数据集上的行数,而不是不同的Staff_Att_Status的计数。例如,当前数据集中的数据总是为1,因为那里只有“存在”状态。