在where子句中无法访问按变量分区

时间:2019-05-01 22:57:27

标签: sql-server dense-rank partition-by

SELECT DISTINCT
    cs.file_id,  
    null, 
    'lol', 
    t.encounter_id, 
    e.pan, e.mr, 
    e.provider_id, 
    t.c_date_of_service, 
    GETDATE(),
    ROW_NUMBER() OVER (PARTITION BY e.encounter_id ORDER BY e.encounter_id DESC) row
FROM 
    encounters e WITH (NOLOCK)
JOIN 
    dummy ec ON ec.encounter_id = e.encounter_id
JOIN 
    case_status cs ON cs.case_id = ec.case_id
JOIN 
    (SELECT DISTINCT
         e.encounter_id, c.date_of_service AS c_date_of_service
     FROM 
         encounters e WITH (NOLOCK)
     JOIN 
         dummy ec ON ec.encounter_id = e.encounter_id
     JOIN 
         cases c ON ec.case_id = c.case_id
     GROUP BY
         e.pid, c.date_of_service, e.encounter_id
     HAVING
         (COUNT(0) > 1 AND e.pid IS NOT NULL)) AS t ON t.encounter_id = e.encounter_id
WHERE
    row = 1

我遇到错误

  

无效的列名“行”

如果我只删除where row = 1,它在SQL Server中可以正常工作。

另一件事-ROW_NUMBER() OVER (PARTITION BY e.encounter_id ORDER BY e.encounter_id DESC)显示不同的行号,RANK() OVER (PARTITION BY e.encounter_id ORDER BY e.encounter_id DESC)显示所有等级为1,其中结果数据中有重复的encounter_id

1 个答案:

答案 0 :(得分:-1)

您不能直接在where子句中使用计算列,需要将其包装在内联查询中,然后在其上添加where子句。

select * from (SELECT DISTINCT
        cs.file_id,  
        null, 
        'lol', 
        t.encounter_id, 
        e.pan, e.mr, 
        e.provider_id, 
        t.c_date_of_service, 
        GETDATE(),
        ROW_NUMBER() OVER (PARTITION BY e.encounter_id ORDER BY e.encounter_id DESC) row
    FROM 
        encounters e WITH (NOLOCK)
    JOIN 
        dummy ec ON ec.encounter_id = e.encounter_id
    JOIN 
        case_status cs ON cs.case_id = ec.case_id
    JOIN 
        (SELECT DISTINCT
             e.encounter_id, c.date_of_service AS c_date_of_service
         FROM 
             encounters e WITH (NOLOCK)
         JOIN 
             dummy ec ON ec.encounter_id = e.encounter_id
         JOIN 
             cases c ON ec.case_id = c.case_id
         GROUP BY
             e.pid, c.date_of_service, e.encounter_id
         HAVING
                 (COUNT(0) > 1 AND e.pid IS NOT NULL)) AS t ON t.encounter_id = 
                          e.encounter_id

        ) as A WHERE A.row = 1