如何在SQL Server中使用计数查找百分比

时间:2018-09-16 21:24:19

标签: mysql sql sql-server

我有两个表,一个表用于图书馆成员,另一个表用于借出。这些表已加入图书馆会员编号,我需要找到从图书馆借阅至少一本书的会员所占的百分比。

我已经知道“贷款”表中有645个不同的会员号,而“会员”表中有2000个不同的会员号。如此说来,当我运行以下查询时,我得到的结果为0:

SELECT 
    COUNT(DISTINCT L.Member_no) / COUNT(M.Member_no) as 'Percentage'
FROM 
    Reservations.Loan AS L
JOIN
    Members.Member AS M ON L.Member_No = M.Member_no;

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

select CAST(COUNT(distinct L.Member_no) AS NUMERIC(10, 2)) / COUNT(M.Member_no) as 'Percentage'

那是因为整数运算。转换为带小数的数字,它将起作用。

答案 1 :(得分:1)

这应该有效:

select COUNT(distinct L.Member_no) * 100 / COUNT(distinct M.Member_no) as 'Percentage' from Reservations.Loan as L, Members.Member as M

1)您想要百分比,因此需要将分子乘以100,否则将得到一个小数。

2)如果您加入表Member_no,那么您只有一个表,对它们进行计数并除以100%即可得到

===

您可以通过尝试here

这两个查询来对此进行测试

查询1:

select COUNT(distinct O.CustomerID) * 100 / COUNT(distinct C.CustomerID) as 'Percentage' from Orders as O, Customers as C

查询1:

select COUNT(distinct O.CustomerID) * 100 / COUNT(distinct C.CustomerID) as 'Percentage' from Orders as O join Customers as C on O.CustomerID = C.CustomerID

编辑:我刚刚意识到我的方法仅在MySQL中有效,而在MSSQL中,显然您需要转换。