我正在尝试使用 sql 中的 count 函数将一些数据分三部分获取到我的 asp.net 项目中:
第一部分将使用第一个 SQL 查询,如下所示:
select distict, shop_number, count(Emp_id)
from Shops_and_Employee_Table
group by distict, shop_number
第二部分将使用第二个 SQL 查询:
select distict, shop_number, count(Emp_id)
from Shops_and_Employee_Table
where score >= 80
group by distict, shop_number
我在我的项目中的 2 个不同的 GridView 中显示上述结果。
现在我需要显示一个新的 GridView 来获取第二个查询与第一个查询相比的平均值,我使用了以下命令,但没有得到正确的结果:
select
a.distict, a.shop_number, b.number / a.number
from
(select distict, shop_number, count(Emp_id) as number
from Shops_and_Employee_Table
group by distict, shop_number) a
join
(select distict, shop_number, count(Emp_id) as number
from Shops_and_Employee_Table
where score >= 80
group by distict, shop_number) b on a.shop_number = b.shop_number
有人可以告诉我我在平均查询中写了什么吗?或者建议我是否应该对 C# 代码中的数字进行平均,但解释一下如何做,因为我不知道如何应用它。
等待您的大力帮助。
我尝试用 SQL 本身来做,但我得到了错误的数字,有人告诉我在后面的 C# 代码中做得更好,但我做不到,请帮忙。
您可以使用条件聚合来组合两个查询。
select
se.distict,
se.shop_number,
count(*) as TotalCount,
count(case when se.score >= 80 then 1 end) as Over80Count,
count(case when se.score >= 80 then 1 end) * 1.0 / count(*) as Percent
from Shops_and_Employee_Table se
group by
se.distict,
se.shop_number;
在 Postgres 和其他一些数据库中,您可以使用
FILTER
语法代替。
如果您也通过
distict
加入,并使用 left join
,并通过乘以 decimal
转换为 1.0
,那么您的原始代码将会工作,尽管效率相当低。