Getting two counts and then dividing them

后端 未结 5 1499
攒了一身酷
攒了一身酷 2021-02-08 01:17

I am attempting to get two counts and then divide those two counts to get the ratio of the items I am counting. I saw this post here and tried that. I am getting an error in my

相关标签:
5条回答
  • 2021-02-08 01:58

    use below piece of query instead

    SELECT
    A.NUM, A.DENOM, cast(A.NUM as float)/cast(A.DENOM as float)
    
    FROM
    (
    -- COLUMN SELECTION. TWO NUMBERS WILL REPRESENT A NUM AND A DENOM
    SELECT 
        (SELECT COUNT(DRG_NO)
            FROM smsdss.BMH_PLM_PtAcct_V
            WHERE drg_no IN (061,062,063,064,065,066)
            AND Adm_Date BETWEEN @SD AND @ED
            AND PLM_PT_ACCT_TYPE = 'I')
            AS NUM,
        (SELECT COUNT(DRG_NO)
            FROM smsdss.BMH_PLM_PtAcct_V
            WHERE drg_no IN (061,062,063,064,065,066,067,068,069)
            AND Adm_Date BETWEEN @SD AND @ED
            AND Plm_Pt_Acct_Type = 'I')
            AS DENOM
    )A
    

    the issue is if num and denom are both INT, the division will return INT as well, so converting one (or both) of them to float will result in having float as division result

    0 讨论(0)
  • 2021-02-08 02:02

    The ratio of two integers will be an integer. For example: 10/20 = 0.5 = 0. You need to cast your ratio into a float in order to get an accurate answer.

    0 讨论(0)
  • 2021-02-08 02:13

    Use SELECT A.NUM, A.DENOM, cast(A.NUM as float)/cast(A.DENOM as float)

    SQL Server consider that A.NUM / A.DENOM are int, because A.NUM and A.DENUM are int

    0 讨论(0)
  • 2021-02-08 02:19

    The structure of your query bothers me. You can do it much more efficiently as:

    SELECT A.NUMer, A.DENOM, cast(A.NUMer as float)/A.DENOM 
    FROM (SELECT COUNT(case when drg_no IN (061,062,063,064,065,066) then DRG_NO
                       end ) as Numer,
                 count(case when drg_no IN 061,062,063,064,065,066,067,068,069) then DRG_NO
                       end) as denom
          FROM smsdss.BMH_PLM_PtAcct_V
          WHERE drg_no IN (061,062,063,064,065,066)
            AND Adm_Date BETWEEN @SD AND @ED
            AND PLM_PT_ACCT_TYPE = 'I'
         ) a
    

    This doesn't affect the integer divide issue, but your original query is overcomplicated.

    0 讨论(0)
  • 2021-02-08 02:19

    It's truncating due to integer division. You can perform regular division by casting.

    INSERT INTO @TABLE1
    SELECT
    A.NUM, A.DENOM, CAST(A.NUM AS FLOAT)/A.DENOM 
    
    0 讨论(0)
提交回复
热议问题