2 @@ RowCounts的百分比

时间:2017-05-18 16:45:09

标签: sql sql-server tsql sql-server-2012

我试图获得这两个表的百分比行数。理想情况下,我只想看到百分比而没有别的。

这是我没有运气的尝试。

Select Distinct ID
from dbo.1
Where StartDate between '2014-04-01' and '2017-04-30'
and Status  = 'ATTENDED'
order by ID

SELECT @@ROWCOUNT AS 'Rowcount1'


Select Distinct ID
from dbo.1
Where Acitve = 'Y'
and StartDate between '2014-04-01' and '2017-04-30'
and Status = 'ATTENDED'
order by EmrID

SELECT @@ROWCOUNT AS 'RowCount2'

SELECT 'RowCount1' / 'RowCount2' AS Percentage

3 个答案:

答案 0 :(得分:4)

为什么要尝试使用@@rowcount?相反,某些条件聚合呢?

select 
    AllCount    = count(*)
  , ActiveCount = count(case when Active='Y' then 1 end)
  , Percentage  = avg(case when Active='Y' then 1.0 else 0.0 end)
from dbo.t
where StartDate >= '2014-04-01' 
  and StartDate <= '2017-04-30'
  and Status = 'ATTENDED'

另外,请注意betweenWhat do between and the devil have in common? - Aaron Bertrand

答案 1 :(得分:3)

如果您不需要select distinct,那么SQLZim的答案是正确的。如果你这样做,那么你需要调整答案。这是一种方式:

select count(*) as RowCount
       count(distinct case when Active = 'Y' then id end) as ActiveCount,
       count(distinct case when Active = 'Y' then id end) * 1.0 / count(distinct id) 
from dbo.1
where StartDate >= '2014-04-01' and StartDate <= '2017-04-30' and
      Status = 'ATTENDED';

答案 2 :(得分:1)

如果您只想要百分之百试试这个:

SELECT 
       ( 
              SELECT CONVERT(FLOAT, Count(DISTINCT id))
              FROM   dbo.1 
              WHERE  startdate BETWEEN '2014-04-01' AND    '2017-04-30' 
              AND    status = 'ATTENDED') / 
       ( 
              SELECT CONVERT(FLOAT, count(DISTINCT id))
              FROM   dbo.1 
              WHERE  acitve = 'Y' 
              AND    startdate BETWEEN '2014-04-01' AND    '2017-04-30' 
              AND    status = 'ATTENDED') AS percentage

如果您还想要个别值,请尝试以下方法:

DECLARE @val1 INT;
DECLARE @val2 INT;

SELECT @val1 = Count(DISTINCT id) 
FROM   dbo.1 
WHERE  startdate BETWEEN '2014-04-01' AND    '2017-04-30' 
AND    status = 'ATTENDED'

SELECT @val2 = count(DISTINCT id) 
FROM   dbo.1 
WHERE  acitve = 'Y' 
AND    startdate BETWEEN '2014-04-01' AND    '2017-04-30' 
AND    status = 'ATTENDED'

SELECT @val1 AS val1, @val2 AS val2, CONVERT(FLOAT, @val1) / CONVERT(FLOAT, @val2) AS percent

由于您关注的只是计数,因此不需要按语句排序。

使用CTE也可以减少这种情况:

;WITH

base AS (
    SELECT id, acitve
    FROM   dbo.1 
              WHERE  startdate BETWEEN '2014-04-01' AND    '2017-04-30' 
              AND    status = 'ATTENDED'
)

SELECT 
       ( 
              SELECT CONVERT(FLOAT, Count(DISTINCT id))
              FROM   base) / 
       ( 
              SELECT CONVERT(FLOAT, count(DISTINCT id))
              FROM   base
              WHERE  acitve = 'Y') AS percentage