我试图得到两个计数,然后将这两个计数除以得到我计算的项目的比率。我看到了这篇文章here并试了一下。我的结果中出现错误,没有错误消息只是错误的数字。我正在使用SQL-Server 2008
这是我的代码:
-- INTERNAL PEPPER REPORT
--#####################################################################
-- VARIABLE DECLARATION AND INITIALIZATION
DECLARE @SD DATETIME
DECLARE @ED DATETIME
SET @SD = '2013-01-01'
SET @ED = '2013-03-31'
-- TABLE DECLARATION ##################################################
DECLARE @TABLE1 TABLE(NUMERATOR INT, DENOMINATOR INT, RATIO INT)
--#####################################################################
-- WHAT GETS INSERTED INTO TABLE 1
INSERT INTO @TABLE1
SELECT
A.NUM, A.DENOM, A.NUM/A.DENOM
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
SELECT NUMERATOR, DENOMINATOR, RATIO
FROM @TABLE1
计数产生并正确显示,但是对于一个比例,我得到0并且不确定为什么我得到它。
谢谢,
答案 0 :(得分:15)
使用SELECT A.NUM, A.DENOM, cast(A.NUM as float)/cast(A.DENOM as float)
SQL Server认为A.NUM / A.DENOM在,因为A.NUMBER和A.NUM是int
答案 1 :(得分:3)
您的查询结构困扰我。你可以更有效地做到:
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
这不会影响整数除法问题,但原始查询过于复杂。
答案 2 :(得分:1)
两个整数的比率是整数。例如:10/20 = 0.5 = 0.您需要将比率转换为浮点数才能得到准确答案。
答案 3 :(得分:1)
由于整数除法而截断。你可以通过施法来定期进行分割。
INSERT INTO @TABLE1
SELECT
A.NUM, A.DENOM, CAST(A.NUM AS FLOAT)/A.DENOM
答案 4 :(得分:1)
改为在下面的查询中使用
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
问题是,如果num和denom都为INT,则除法也会返回INT,因此将其中一个(或两个)转换为float会导致float为除法结果