使用top 1给我部分数据,但是如果我不使用top 1,它将返回子查询返回的错误

时间:2018-08-17 14:43:06

标签: sql sql-server tsql

在下面的查询中,使用前1个返回我的数据,但是我仍然想念一些帐户的医师代码,但是ifi不要使用前1个,它返回了我的值子查询,返回的返回值超过1个错误/ ..帮助我解决它。

SELECT DISTINCT
       FacilityID,
       patient_billing_identifier,
       ProcedureID AS Proc_cd,
       LTRIM(RTRIM(CONVERT(varchar(10), OperationDateTime, 101))) AS proc_date,
       CASE
            WHEN ProcedureSeqID = '1' THEN '0'
            WHEN ProcedureSeqID = '2' THEN '1'
            WHEN ProcedureSeqID = '3' THEN '2'
            WHEN ProcedureSeqID = '4' THEN '3'
            WHEN ProcedureSeqID = '5' THEN '4'
            WHEN ProcedureSeqID = '6' THEN '5'
            WHEN ProcedureSeqID = '7' THEN '6'
            WHEN ProcedureSeqID = '8' THEN '7'
            WHEN ProcedureSeqID = '9' THEN '8'
            WHEN ProcedureSeqID = '10' THEN '9'
            WHEN ProcedureSeqID = '11' THEN '10'
            WHEN ProcedureSeqID = '12' THEN '11'
            WHEN ProcedureSeqID = '13' THEN '12'
            WHEN ProcedureSeqID = '14' THEN '13'
            WHEN ProcedureSeqID = '15' THEN '14'
            WHEN ProcedureSeqID = '16' THEN '15'
            WHEN ProcedureSeqID = '17' THEN '16'
            WHEN ProcedureSeqID = '18' THEN '17'
            WHEN ProcedureSeqID = '19' THEN '18'
            WHEN ProcedureSeqID = '20' THEN '19'
            WHEN ProcedureSeqID = '21' THEN '20'
            WHEN ProcedureSeqID = '22' THEN '21'
            WHEN ProcedureSeqID = '23' THEN '22'
            WHEN ProcedureSeqID = '24' THEN '23'
            ELSE ''
       END AS SeqNum,
       '"' + LTRIM(RTRIM(ProviderID)) + '"' AS PhysicianCode,
       '10' AS [ICDType]
INTO #EOPPRy
FROM EOPPR1
     INNER JOIN AbsOvOperativeEpisodes VPM317 (NOLOCK) ON VPM317.VisitID = EOPPR1.VisitID;


SELECT FacilityID,
       patient_billing_identifier,
       Proc_cd,
       CASE
            WHEN proc_date IS NULL THEN (SELECT TOP 1
                                                proc_date
                                         FROM #EOPPRy
                                         WHERE patient_billing_identifier = T.patient_billing_identifier
                                           AND proc_date IS NOT NULL
                                         ORDER BY patient_billing_identifier DESC)
            ELSE proc_date
       END AS proc_date,
       SeqNum,
       PhysicianCode,
       ICDType
INTO EOPPR3
FROM #EOPPRy T
ORDER BY patient_billing_identifier;

1 个答案:

答案 0 :(得分:0)

尝试将前1个proc_date替换为max(proc_date)

在该点上,子查询中只能有一个标量结果。

如果没有返回您期望的结果,是因为原始查询中存在问题。 检查#EOPPR中的内容,并确保获得所需的信息。

选择最大值(proc_date)                                          来自#EOPPRy                                          其中Patient_billing_identifier = T.patient_billing_identifier                                            AND proc_date不为空                                          ORDER BY Patient_billing_identifier DESC

希望对您有帮助。