从两个表的计数计算百分比

时间:2018-12-03 09:08:34

标签: sql-server group-by

我有以下代码可以从两个表中返回计数

USE CBA

SELECT
    COUNT(DISTINCT dat.CoAc) AS Count1
FROM
    (SELECT *
     FROM IR20181125
     WHERE pdate NOT IN ('NULL','')) dat

SELECT
    COUNT(DISTINCT CoAc) As Count2
FROM 
    IPR20181125

我需要计算百分比(Count1 * 100)/ Count2,但是我不确定这样做的语法。

编辑-我需要正确的答案到小数点后2位。

2 个答案:

答案 0 :(得分:1)

您无需单独选择即可获得这些计数。您可以立即获得它们:

Select
    COUNT(DISTINCT case when pdate not in ('NULL','') then CoAc else NULL end) As Count1
    , COUNT(DISTINCT CoAc) As Count2
From IR20181125

因此,您可以直接计算百分比:

Select COUNT(DISTINCT case when pdate not in ('NULL','') then CoAc else NULL end) * 100.0 / COUNT(DISTINCT CoAc)
From IR20181125

如果您的计数来自不同的表,则可以使用子查询来计算两个计数,并使用不包含from的单选来计算百分比:

select 
    100.0 * (
        Select COUNT(DISTINCT CoAc) as Cnt
        From IR20181125
        where pdate not in ('NULL','')
    ) / (
        select COUNT(DISTINCT CoAc) as Cnt
        from SecondTable
    )

答案 1 :(得分:1)

select (
 Select (COUNT(DISTINCT dat.CoAc) * 100) AS Count1 /*count1 * 100*/
 From(
  Select *
  From IR20181125
  where pdate not in ('NULL','')
 ) dat
) / (
 Select COUNT(DISTINCT CoAc) As Count2
 From IPR20181125
) CountPercentage

让我知道,你得到了什么。

更新1

select (
 Select convert (decimal (18,2), (COUNT(DISTINCT dat.CoAc) * 100)) AS Count1 
 From(
  Select *
  From IR20181125
  where pdate not in ('NULL','')
 ) dat
) / (
 Select convert (decimal (18,2), COUNT(DISTINCT CoAc)) As Count2
 From IPR20181125
) CountPercentage