在SQL中使用虚拟对象

时间:2019-06-06 14:37:36

标签: sql sql-server ssms

我试图找出两列不相同的行的分数:

此代码给出一个或零(取决于我如何定义虚拟对象):

SELECT CAST(AVG(subq.ens) AS DECIMAL(10,7))
from (select INDDATO_DATO, INDTIDSPUNKT_DRGKONTAKT_DATO, LeveranceDato_DATO, 
    case 
    when INDDATO_DATO = INDTIDSPUNKT_DRGKONTAKT_DATO THEN 1
    else 0
    end as ens
    FROM [Patient_kval].[DRG2018].[V_DRG2018_DRGKONTAKTER]
    where LeveranceDato_DATO= '2019-03-27'
    ) subq

但是我已经通过两次计数和除法解决了这个问题,结果是35%。即我已经做到了:

SELECT count(*)
FROM [Patient_kval].[DRG2018].[V_DRG2018_DRGKONTAKTER]
where LeveranceDato_DATO= '2019-03-27' and INDDATO_DATO = INDTIDSPUNKT_DRGKONTAKT_DATO; -- 1.954.352


SELECT count(*)
FROM [Patient_kval].[DRG2018].[V_DRG2018_DRGKONTAKTER]
where LeveranceDato_DATO= '2019-03-27';-- 5.441.763

但是我想知道第一种方法的问题。

1 个答案:

答案 0 :(得分:1)

您要获取avg的整数,结果将转换为整数,请参见https://docs.microsoft.com/en-us/sql/t-sql/functions/avg-transact-sql?view=sql-server-2017。请改用十进制常数。

SELECT CAST(AVG(subq.ens) AS DECIMAL(10,7))
from (select INDDATO_DATO, INDTIDSPUNKT_DRGKONTAKT_DATO, LeveranceDato_DATO, 
    case 
    when INDDATO_DATO = INDTIDSPUNKT_DRGKONTAKT_DATO THEN 1.0
    else 0.0
    end as ens
    FROM [Patient_kval].[DRG2018].[V_DRG2018_DRGKONTAKTER]
    where LeveranceDato_DATO= '2019-03-27'
    ) subq