SQL Server 中的条件计数与 WHERE 子句
在 SQL Server 中,可以使用 COUNT()
聚合函数结合 WHERE
子句来统计满足特定条件的记录数。
以下示例的目标是统计 MyColumn
值等于 1 的记录数。以下是修改后的查询:
<code class="language-sql">SELECT UID, COUNT(UID) AS TotalRecords, SUM(ContractDollars) AS ContractDollars, (SELECT COUNT(*) FROM dbo.AD_CurrentView AS Sub WHERE Sub.UID = Outer.UID AND Sub.MyColumn = 1) * 100.0 / COUNT(UID) AS PercentageOfOne FROM dbo.AD_CurrentView AS Outer GROUP BY UID HAVING SUM(ContractDollars) >= 500000</code>
以下是查询的步骤分解:
MyColumn
= 1) 的记录数。UID
列将主查询与子查询连接。MyColumn
等于 1 的记录的百分比。 注意,这里将除数 100
改为 100.0
以确保浮点型除法,得到更精确的百分比结果。PercentageOfOne
列。This revised query avoids potential integer division issues by using 100.0
instead of 100
in the percentage calculation, ensuring a more accurate floating-point result.
以上是如何在SQL Server中统计满足特定条件的记录并计算百分比?的详细内容。更多信息请关注PHP中文网其他相关文章!